如果我有这张地图

Map<String,String> m2 = new HashMap<String,String>();
    m2.put("2018-02-01", "0");
    m2.put("2018-02-02", "0");
    m2.put("2018-02-03", "1");
    m2.put("2018-02-04", "2");
m2.put("2018-02-05", "2");


我可以通过蒸汽将此地图更改为组列表吗?像这样

Map<String,List<String>>

最佳答案

根据您要基于key还是value进行分组,可以在以下代码中将其交换为groupby

public static void main(String[] args) {
    Map<String, String> m2 = new HashMap<>();
    m2.put("2018-02-01", "0");
    m2.put("2018-02-02", "0");
    m2.put("2018-02-03", "1");
    m2.put("2018-02-04", "2");
    m2.put("2018-02-05", "2");

    Map<String, List<String>> mapList = m2.entrySet().stream().collect(
            Collectors.groupingBy(Map.Entry::getValue, Collectors.mapping(Map.Entry::getKey, Collectors.toList())));
    System.out.println(mapList);
}

关于java - 按值分组,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/55793294/

10-13 05:48