How can I sort a list of maps by value of some specific key using Java 8?

前端 未结 6 2221
情话喂你
情话喂你 2020-12-18 02:46

How can I sort a List of Map using Java 8? The map contains a key called last_name, and the value associated wit

6条回答
  •  执笔经年
    2020-12-18 03:03

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

提交回复
热议问题