-1

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?

Shruti Gusain
  • 67
  • 1
  • 6
  • I see that you are using raw types (e.g. `Map` without type arguments). Several answers already mention this – you should never use raw types, always specify type arguments, i.e. `Map`. – MC Emperor Dec 22 '20 at 09:26

2 Answers2

1

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}]
Eran
  • 387,369
  • 54
  • 702
  • 768
  • output is coming like - [1=ss, 2=ss, 3=bb, 4=cc, 5=ss]. My question was if this statement can be the answer. [{1,ss},{2,ss},{5,ss}] – Shruti Gusain Dec 22 '20 at 08:12
  • @ShrutiGusain See the second part of my answer, that contains `filter`. That would produce the output `[1=ss, 2=ss, 5=ss]`. – Eran Dec 22 '20 at 08:13
  • I want output in the same pattern as shown in my output i.e., entry set inside curly braces. Is this possible? – Shruti Gusain Dec 22 '20 at 08:15
  • @ShrutiGusain what do you want the type of the output List to be? `List>` or `List`? That would affect my answer. – Eran Dec 22 '20 at 08:16
  • The output should be in a pattern like - [ {EntrySet.key , EntrySet.Value } , {EntrySet.key , EntrySet.Value } ] – Shruti Gusain Dec 22 '20 at 08:19
  • Yeah, it worked. Thanks. I thought it has something to do with Grouping but it can be done using joining too. Great – Shruti Gusain Dec 22 '20 at 08:24
0

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); 
        } 
Tomer Li-ran
  • 11
  • 2
  • 7
  • The output should be in a pattern like - [ {EntrySet.key , EntrySet.Value } , {EntrySet.key , EntrySet.Value } ] and yeah, sorry I need this to be done using streams – Shruti Gusain Dec 22 '20 at 08:21