dictionary - 将地图的条目分组到列表中
问题描述
假设我有一个带有一些条目的 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}]
可能吗?
解决方案
当然是:
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}]
推荐阅读
- python - 是否可以在 networkx 中获得路径中包含属性的唯一路径?
- javascript - 当位置固定和“顶部”属性设置时,动画元素在 Safari 中不可见
- c# - 动态内容的 WPF ContentControl 绑定无法正常工作
- r - R:如何简单地比较 2 个数据框中列的值
- javascript - 当计数器达到 1000+ 时添加点分隔符
- c# - .Net 通过字符串变量访问实例化的类成员
- import - 尝试运行加密警报“没有名为 urllib3 的模块
- c# - 使用递归函数判断传入的值是否是游戏中可能的分数
- asp.net-mvc - 由于拆分架构导致的 WebAuthn 问题
- visual-studio-2019 - VS 2019 和 SAP HANA 数据源