首页 > 解决方案 > 将地图的条目分组到列表中

问题描述

假设我有一个带有一些条目的 HashMap:

Map hm= new HashMap();
hm.put(1,"ss");
hm.put(2,"ss");
hm.put(3,"bb");
hm.put(4,"cc");
hm.put(5,"ss");

我想要像这样的输出:

[{1,ss},{2,ss},{5,ss}]

可能吗?

标签: dictionaryjava-8java-streamgroupingentryset

解决方案


当然是:

List<Map.Entry<Integer,String>> list =
    hm.entrySet().stream().collect(Collectors.toList());

您应该将您的定义更改Map为:

Map<Integer,String> hm = new HashMap<>();

PS您没有指定是想要输出中的所有条目List,还是只想要其中的一些。在示例输出中,您仅包含具有“ss”值的条目。这可以通过添加过滤器来实现:

List<Map.Entry<Integer,String>> list =
    hm.entrySet().stream().filter(e -> e.getValue().equals("ss")).collect(Collectors.toList());
System.out.println (list);

输出:

[1=ss, 2=ss, 5=ss]

编辑:您可以List按所需格式打印,如下所示:

System.out.println (list.stream ().map(e -> "{" + e.getKey() + "," + e.getValue() + "}").collect (Collectors.joining (",", "[", "]")));

输出:

[{1,ss},{2,ss},{5,ss}]

推荐阅读