如何使用Java 8对地图列表进行排序?

时间:2017-06-13 19:47:12

标签: java sorting java-8

如何使用Java 8对List Map<String, String>进行排序?地图包含名为last_name的密钥,与其关联的值可能为null。我不知道该怎么做,因为以下会导致编译错误:

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

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

使用匿名类是唯一的方法吗?

请注意,我尝试对列表中的每个地图进行排序。我想根据每个地图中的一个键对列表进行排序。

6 个答案:

答案 0 :(得分:9)

看起来您可以像

那样重写代码
peopleList.sort(Comparator.comparing(
                    m -> m.get("yourKey"), 
                    Comparator.nullsLast(Comparator.naturalOrder()))
               )

答案 1 :(得分: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值排在第一位或最后一位,请切换-1null

为了彻底,我添加了有用测试用例的生成器:

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

答案 2 :(得分:2)

由于您的peopleList可能包含nullMap::key可能包含空值,因此您可能需要nullsLast两次:

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

答案 3 :(得分:0)

您可以覆盖Collection的de compare方法。 这是一个例子: https://www.mkyong.com/java8/java-8-lambda-comparator-example/

您必须比较对象的last_name,并且不要忘记正确处理null。

答案 4 :(得分:-2)

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

答案 5 :(得分:-2)

试试这个:

按键:

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

按值:

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