Sorting in Java 7 vs Java 8

This post is around Sorting in Java7 vs Java 8.

For explanation, i ll take a List as Data Structure input.

List<String> nameofCricketers=new ArrayList<String>();
nameofCricketers.add(“Virat”);
nameofCricketers.add(“Rohit”);
nameofCricketers.add(“Ajinkya”);
nameofCricketers.add(“Bumrah”);

Now we will create two methods to explain the same.

void java7Sorting(List<String> nameofCricketers);
void java8Sorting(List<String> nameofCricketers);

In Java 7 , When we had to implement sorting, below is the Code which we had to write.

private void java7Sorting(List<String> nameofCricketers){
Collections.sort(nameofCricketers,new Comparator<String>(){

@Override
public int compare(String c1,String c2){
return c1.compareTo(c2)
          }
     }
}

After inclusion of lambda functions in java8 , it can be done quickly by a single line of code.

private void java8Sorting(List<String> nameofCricketers){
Collections.sort(nameofCricketers,(c1,c2) -> c1.compareTo(c2));

}

Output would be same on both execution.

[Ajinkya, Bumrah, Rohit, Virat]

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 )

Google photo

You are commenting using your Google 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 )

Connecting to %s

This site uses Akismet to reduce spam. Learn how your comment data is processed.

%d bloggers like this:
search previous next tag category expand menu location phone mail time cart zoom edit close