How can I sort a List
of Map
using Java 8? The map contains a key called last_name
, and the value associated wit
You can override de compare method of the Collection. Here is an example: https://www.mkyong.com/java8/java-8-lambda-comparator-example/
You will have to compare the last_name of the objects, and do not forget to handle the null properly.
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);
});
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()))));
Steps to sort a Map in Java 8.
1]Convert a Map into a Stream
2]Sort it
3]Collect and return a new LinkedHashMap (keep the order)
Map result = map.entrySet().stream()
.sorted(Map.Entry.comparingByKey())
.collect(Collectors.toMap(Map.Entry::getKey, Map.Entry::getValue,
(oldValue, newValue) -> oldValue, LinkedHashMap::new));
It looks like you can rewrite your code like
peopleList.sort(Comparator.comparing(
m -> m.get("yourKey"),
Comparator.nullsLast(Comparator.naturalOrder()))
)
Try this:
By Keys:
Map<String, String> result = unsortMap.entrySet().stream()
.sorted(Map.Entry.comparingByKey())
.collect(Collectors.toMap(Map.Entry::getKey, Map.Entry::getValue,
(oldValue, newValue) -> oldValue, LinkedHashMap::new));
By Values:
Map<String, String> result = unsortMap.entrySet().stream()
.sorted(Map.Entry.comparingByValue(Comparator.reverseOrder()))
.collect(Collectors.toMap(Map.Entry::getKey, Map.Entry::getValue,
(oldValue, newValue) -> oldValue, LinkedHashMap::new));