How can I sort a list of maps by value of some specific key using Java 8?
This should fit your requirement.
peopleList.sort((o1, o2) -> o1.get("last_name").compareTo(o2.get("last_name")));
In case you want handle the null pointer try this "old fashion" solution:
peopleList.sort((o1, o2) ->
{
String v1 = o1.get("last_name");
String v2 = o2.get("last_name");
return (v1 == v2) ? 0 : (v1 == null ? 1 : (v2 == null ? -1 : v1.compareTo(v2))) ;
});
Switch 1
and -1
if you want the null
values first or last.
For thoroughness' sake I've added the generator of useful test cases:
Random random = new Random();
random.setSeed(System.currentTimeMillis());
IntStream.range(0, random.nextInt(20)).forEach(i -> {
Map<String, String> map1 = new HashMap<String, String>();
String name = new BigInteger(130, new SecureRandom()).toString(6);
if (random.nextBoolean())
name = null;
map1.put("last_name", name);
peopleList.add(map1);
});
It looks like you can rewrite your code like
peopleList.sort(Comparator.comparing(
m -> m.get("yourKey"),
Comparator.nullsLast(Comparator.naturalOrder()))
)
Since your peopleList
might contain a null
and the Map::key
might have a null value, you probably need to nullsLast
twice:
peopleList.sort(Comparator.nullsLast(Comparator.comparing(m -> m.get("last_name"),
Comparator.nullsLast(Comparator.naturalOrder()))));