How can I sort the list of maps using Java 8?

How can I sort Listout Map<String, String>using Java 8? The card contains a key with a name last_name, and the value associated with it can be null. I am not sure how to do this because the following results in a compiler error:

List<Map<String, String>> peopleList = ...

peopleList.sort(Comparator.comparing(Map::get, Comparator.nullsLast(Comparator.naturalOrder())));

Is using an anonymous class the only way to do this?

Please note that I am not trying to sort each card in the list. I want to sort the list based on the key on each map.

+4
source share
6 answers

It looks like you can rewrite your code as

peopleList.sort(Comparator.comparing(
                    m -> m.get("yourKey"), 
                    Comparator.nullsLast(Comparator.naturalOrder()))
               )
+7
source

peopleList null, Map::key , , , nullsLast :

peopleList.sort(Comparator.nullsLast(Comparator.comparing(m -> m.get("last_name"),
                            Comparator.nullsLast(Comparator.naturalOrder()))));
+2

.

peopleList.sort((o1, o2) -> o1.get("last_name").compareTo(o2.get("last_name")));

, "" :

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))) ;
});

1 -1, , null .

:

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);
});
+1
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));
-2
source

Try the following:

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));
-2
source

Source: https://habr.com/ru/post/1679184/


All Articles