Thursday, April 17, 2014
Today I am going to deal with the new feature of Java 8 - Lambda Expression. Here we will go through a short introduction on lambda expression and follow up with a simple example to start with it before going into complex ones in our next articles.
Why Lambda Expressions ?Earlier befor Java 8, when we didn't have this awesome feature we had to use anonymous inner classes. Suppose you are writing a GUI application where you write anony mous class very often to specify what action is to be taken when a button is clicked. But now we can use lambdas in places of anonymous classes having a single method. Alternatively you can use them for functional interfaces.In those cases normally we try to pass funtionality as function arguments using anonymous classes. But those codes are cumbersome and look very unclear. So Lambda Expressions has been introduced which allows you to pass functionality as arguments with very simple syntax.
What is the syntax of Lambda Expression ?
Suppose you have a functional interfacelike below which takes a string argument and returns void.
interface IDemo{ public void action(String s); }Now your lambda expression syntax in place of anonymous class is
(a) -> System.out.println(s)Now if you have more than one parameter then give them seperated by commas as (a,b,c) and so on. As in our case we have only one parameter, you can omit the parenthesis.
Here in our sample example we will create a Song class which will have different attrbutes like tile,album etc. There will be a functional interface that takes a Song object and returns a boolean value. Now there will be a method which takes in a Collection of songs and performs a particular action when they satisfy a particular criteria. Now earlier, you woula have to pass the criteria while calling that function as an anonymous class; but with Java 8 we will do it using Lambda Expression.
-------------------------------------------------------------------------------------------------------------------------
Java Source Code
-------------------------------------------------------------------------------------------------------------------------package lambda; import java.util.List; import java.util.ArrayList; public class Song { //instance variables private String title,artist,album; private short year,bitrate; //constructor to set values public Song(String title, String artist, String album, short year, short bitrate) { super(); setTitle(title); setArtist(artist); setAlbum(album); setYear(year); setBitrate(bitrate); } public String getTitle() { return title; } public void setTitle(String title) { this.title = title; } public String getArtist() { return artist; } public void setArtist(String artist) { this.artist = artist; } public String getAlbum() { return album; } public void setAlbum(String album) { this.album = album; } public short getYear() { return year; } public void setYear(short year) { this.year = year; } public short getBitrate() { return bitrate; } public void setBitrate(short bitrate) { this.bitrate = bitrate; } @Override public String toString() { return "Music [title=" + title + ", artist=" + artist + ", album=" + album + ", year=" + year + ", bitrate=" + bitrate + "]"; } //prints all songs of the list which satisfies the criteria of tester public static void printSongs(List<Song> tracks, CheckSong tester){ for(Song mt : tracks) //for-each loop if(tester.test(mt)) //testing criteria System.out.println(mt); //printing if satisfies } } //functional interface to check the criteria interface CheckSong{ boolean test(Song song); }Now earlier you had to mention the criteria by anonymous class like this while calling printSongs() method. Here we are trying to print all songs in list that are released after year 2010.
printSongs(tracks, new CheckSong() { @Override public boolean test(Song song) { return song.getYear() > 2010; } });But now with lambda expression the whole thing looks much simpler as shown below
printSongs(tracks, mt -> mt.year > 2010);The main method of the Song class where both approaches are shown
public static void main(String... args){ List<Song> tracks = new ArrayList<>(); Song m = new Song("Waka Waka","Shakira","FIFA",(short)2010,(short)320); tracks.add(m); m = new Song("La La La","Shakira","FIFA",(short)2014,(short)320); tracks.add(m); System.out.println("With anonymous class"); printSongs(tracks, new CheckSong() { @Override public boolean test(Song song) { return song.getYear() > 2010; } }); System.out.println("With lambda expression"); printSongs(tracks, mt -> mt.year > 2010); }
-------------------------------------------------------------------------------------------------------------------------
Download Links
-------------------------------------------------------------------------------------------------------------------------Download comlete source from below links which contains Song class with main method where both anonymous class and lambda expressions are used at the same time for better understanding.
DOWNLOAD the source from Mediafire
DOWNLOAD the source from 4shared
Subscribe to:
Post Comments
(Atom)
Total Pageviews
Followers
Labels
- Algorithms (7)
- Annotation (3)
- Files (6)
- Generics (3)
- Graphics2D (5)
- Graphics2D-Images (7)
- Inheritance (2)
- J2EE (9)
- Java 8 (4)
- Java FAQs (19)
- JDBC (3)
- Networking (2)
- Packages (1)
- Reflection (4)
- Security (7)
- Sorting (2)
- Swing (3)
- Threads (3)
- Utils (3)
Popular Posts
-
Today I will show you how you can implement Bankers algorithm in Java. The Banker's algorithm is a resource allocation and deadlock a...
-
------------------------- UPDATE ------------------------- I have updated the code on request of some followers so that they can directly...
-
Today I am going to show how to convert a postfix expression to an infix expression using stack in Java. In an earlier post here we ...
-
Today in this article I will tell you how to convert an infix expression to postfix expression using stack. This is an important applicat...
-
--------------------UPDATE------------------- I have updated my post so that now it can detect IE 11. This modification was necessary as t...
-
Today I am going to show you how you can generate and validate captcha. A CAPTCHA (an acronym for "Completely Automated Public Turin...
-
Today I am going to post a program that will be able to produce all the mColorings of a given graph G. What is mColoring : The problem st...
-
Today in this article I will show you how to create or develop a Tower of Hanoi game in Java. The Tower of Hanoi is a famous problem tha...
0 comments:
Post a Comment