Could somebody show me a quick example how to sort an ArrayList
alphabetically in Java 8 using the new lambda syntax.
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.
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.
Fastest = Collections. sort ; Most Readable = Stream ; Most memory efficient = Collections.
For strings this would work
arrayList.sort((p1, p2) -> p1.compareTo(p2));
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With