Dictionary 将地图的条目分组到列表中

Dictionary 将地图的条目分组到列表中,dictionary,java-8,java-stream,grouping,entryset,Dictionary,Java 8,Java Stream,Grouping,Entryset,假设我有一个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

假设我有一个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());
另外,您没有指定是要输出
列表中的所有条目,还是只需要其中的一部分。在示例输出中,您只包括具有“ss”值的条目。这可以通过添加过滤器来实现:

List<Map.Entry<Integer,String>> list =
    hm.entrySet().stream().filter(e -> e.getValue().equals("ss")).collect(Collectors.toList());
System.out.println (list);
编辑:您可以按以下所需格式打印
列表

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

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

首先,您可以这样声明HashMap:

HashMap<Integer, String> hm = new HashMap<>();
System.out.println("Mappings of HashMap hm1 are : " + hm);
如果要打印键等于1的值,则:

if (hm.containsKey(1)) { 
            String s = hm.get(1); 
            System.out.println("value for key 1 is: " + s); 
        } 

输出是这样的-[1=ss,2=ss,3=bb,4=cc,5=ss]。我的问题是这句话是否可以作为答案。[{1,ss},{2,ss},{5,ss}]@shrutigusa参见我答案的第二部分,其中包含
过滤器
。这将产生输出
[1=ss,2=ss,5=ss]
。我希望输出的模式与我的输出中所示的模式相同,即在花括号内设置条目。这可能吗?@ShrutiGusain您希望输出列表的类型是什么<代码>列表
列表
?这会影响我的答案。输出应该是一种模式,如-[{EntrySet.key,EntrySet.Value},{EntrySet.key,EntrySet.Value}]输出应该是一种模式,如-[{EntrySet.key,EntrySet.Value},{EntrySet.key,EntrySet.Value}],是的,很抱歉,我需要使用stream完成这项工作。我看到您使用的是原始类型(例如,没有类型参数的
Map
)。一些答案已经提到了这一点–您不应该使用原始类型,始终指定类型参数,即
Map
if (hm.containsKey(1)) { 
            String s = hm.get(1); 
            System.out.println("value for key 1 is: " + s); 
        }