Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Sorting ArrayList with Lambda in Java 8

Could somebody show me a quick example how to sort an ArrayList alphabetically in Java 8 using the new lambda syntax.

like image 837
Jeef Avatar asked May 16 '14 18:05

Jeef


People also ask

How do you sort an ArrayList in Java 8?

There are multiple ways to sort a list in Java 8, for example, you can get a stream from the List and then use the sorted() method of Stream class to sort a list like ArrayList, LinkedList, or Vector and then convert back it to List. Alternatively, you can use the Collections. sort() method to sort the list.

How do I sort a list in lambda?

The list. sort() method key parameter is set to lambda. The arguement x is the iterable element ( tuple ) to be sorted by the second element, the number. The lambda expression sorts the list by the second element of the tuple value and updates the original.

What is the most efficient way of sorting a list in Java 8?

Fastest = Collections. sort ; Most Readable = Stream ; Most memory efficient = Collections.


1 Answers

For strings this would work

arrayList.sort((p1, p2) -> p1.compareTo(p2)); 
like image 123
poosliver Avatar answered Sep 21 '22 14:09

poosliver