dictionaryjava-8java-streamgroupingentryset

Group Entries of a map into list


Let's suppose i have a HashMap with some entries:

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:

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

Is it possible?


Solution

  • 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<Integer,String> hm = new HashMap<>();
    

    P.S. You didn't specify whether you want all the entries in the output List, or just some of them. In the sample output you only included entries having "ss" value. 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:

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

    EDIT: You can print that List in the desired format as follows:

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

    Output:

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