Group Entries of a map into list

51 Views Asked by At

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?

2

There are 2 best solutions below

6
Eran On BEST ANSWER

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}]
1
Tomer Li-ran On

Firstly, you declare your HashMap like this:

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

Then after putting the key and the values you can print the whole HashMap it like this:

System.out.println("Mappings of HashMap hm1 are : " + hm);

If you want to print the value where the key is equal to 1 then:

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