Sorting ArrayList with Lambda in Java 8

For strings this would work

arrayList.sort((p1, p2) -> p1.compareTo(p2));

Are you just sorting Strings? If so, you don't need lambdas; there's no point. You just do

import static java.util.Comparator.*;

list.sort(naturalOrder());

...though if you're sorting objects with a String field, then it makes somewhat more sense:

list.sort(comparing(Foo::getString));

Use list.sort(String::compareToIgnoreCase)

Using list.sort(String::compareTo) or list.sort(Comparator.naturalOrder()) will give incorrect (ie. non-alphabetical) results. It will sort any upper case letter before all lower case letters, so the array ["aAAA","Zzz", "zzz"] gets sorted to ["Zzz", "aAAA", "zzz"]


Suppose you have List of names(String) which you want to sort alphabetically.

List<String> result = names.stream().sorted(
                 Comparator.comparing(n->n.toString())).collect(Collectors.toList());

its working perfectly.