[英]Group Entries of a map into list
Let's suppose i have a HashMap with some entries:假设我有一个 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");
i want output like:我想要 output 喜欢:
[{1,ss},{2,ss},{5,ss}]
Is it possible?可能吗?
Of course it is:当然是:
List<Map.Entry<Integer,String>> list =
hm.entrySet().stream().collect(Collectors.toList());
You should change the definition of your Map
to:您应该将Map
的定义更改为:
Map<Integer,String> hm = new HashMap<>();
PS You didn't specify whether you want all the entries in the output List
, or just some of them. PS您没有指定是想要 output List
中的所有条目,还是只想要其中的一些。 In the sample output you only included entries having "ss" value.在示例 output 中,您仅包含具有“ss”值的条目。 This can be achieved by adding a filter:这可以通过添加过滤器来实现:
List<Map.Entry<Integer,String>> list =
hm.entrySet().stream().filter(e -> e.getValue().equals("ss")).collect(Collectors.toList());
System.out.println (list);
Output: Output:
[1=ss, 2=ss, 5=ss]
EDIT: You can print that List
in the desired format as follows:编辑:您可以按所需格式打印该List
,如下所示:
System.out.println (list.stream ().map(e -> "{" + e.getKey() + "," + e.getValue() + "}").collect (Collectors.joining (",", "[", "]")));
Output: Output:
[{1,ss},{2,ss},{5,ss}]
Firstly, you declare your HashMap like this:首先,您像这样声明您的 HashMap:
HashMap<Integer, String> hm = new HashMap<>();
Then after putting the key and the values you can print the whole HashMap it like this:然后在输入键和值之后,您可以像这样打印整个 HashMap :
System.out.println("Mappings of HashMap hm1 are : " + hm);
If you want to print the value where the key is equal to 1 then:如果要打印键等于 1 的值,则:
if (hm.containsKey(1)) {
String s = hm.get(1);
System.out.println("value for key 1 is: " + s);
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.