Java 8 has changed the way to compare objects

before java 8 we used to compare two objects like this

Collections.sort(list,new Comparator<Integer>() {

@Override
public int compare(Integer arg0, Integer arg1) {
return arg1.compareTo(arg0);
}
});

 

again there is a 5 line of boiler  plate code but with java 8 we just have to focus on our business logic below is the example of Comparator using java8

Collections.sort(list, (arg0,arg1) ->arg1.compareTo(arg0));

compiler is enough smart it knows that method compare of Comparator takes two arguments hence we don’t have to tell the compiler about it types it takes the type from our given list and rest is the logic after the symbol ->

Stay tuned for more cool things.

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s