按价值分组地图,请帮助我

时间:2019-04-22 10:59:50

标签: java java-8

如果我有这张地图

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

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

1 个答案:

答案 0 :(得分:2)

根据您要基于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);
}