Short Version
Conceptually something like:
list.sort( StringUtils.compareIgnoreCase(o1.getID(), o2.getID() ));
Long Version
I'm trying to sort a list of thingies:
List<Thingy> list = getListOfThingies();
and thingy has a String
member that i want to sort case-insensitively on:
class Thingy {
private String id;
public getId() { return id; }
}
I know list has a .sort
method:
default void sort(Comparator<? super E> c)
It was enough of a challenge to decipher that syntax, that i managed to cobble together a Comparator<Thingy>
class:
class MyThingySortCompator implements Comparator<Thingy> {
@Override
public int compare(Thingy o1, Thingy o2) {
String s1;
String s2;
if (o1 != null) s1 = o1.getId(); // thingy1 could be null - who knows
if (o2 != null) s2 = o2.getId(); // thingy2 could be null - who knows
//StringUtils handles if a string is null
int compareResult = StringUtils.compareIgnoreCase(s1, s2);
return compareResult;
}
}
and then i can sort my list:
List<Thingy> list = getListOfThingies();
Comparator<Thingy> myThingySortComparator = new MyThingySortCompator();
list.sort(myThingySortComparator);
And that works, but that's quite verbose.
I've heard tell that a lambda syntax can do the same thing, in one line (although be quite unreadable). What would be the equivalent lambda syntax?
Research Effort
- Sorting ArrayList with Lambda in Java 8
- Lambda Comparator Sorting List
- Sorting list of objects from another Class with lambda in Java
- How to sort a List of objects based on one variable using lambda expression?
- Sort a List of Objects by Field in Java
- Sorting arraylist in alphabetical order (case insensitive)
- Sort objects in Java with case sensitive String key