Could somebody show me a quick example how to sort an ArrayList
alphabetically in Java 8 using the new lambda syntax.
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"]
The syntax including a custom comparator is quite simple, and quick, for example here the ArrayList being sorted contains JSONObjects, and I will sort it based on a property called 'order':
arrayList.sort((JSONObject o1, JSONObject o2)->o1.getInt("order")-o2.getInt("order"));
I think this is a really nice and concise syntax, easy to read and less bulky than non-lambda syntax.
List<Product> list = new ArrayList<>();
List<String> list1 = new ArrayList<>();
list.add(new Product(1));
list.add(new Product(2));
list.add(new Product(3));
list.add(new Product(10));
Collections.sort(list, Comparator.comparing((Product p) -> p.id));
for (Product p : list) {
System.out.println(p.id);
}
For strings this would work
arrayList.sort((p1, p2) -> p1.compareTo(p2));
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.
Are you just sorting String
s? 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));