8
HashMap<String, Double> missions = new HashMap<>();
missions.put("name", 1.0);
missions.put("name1", 2.0);
missions.keySet().stream().forEach(el-> System.out.println(el));

This prints only the keys, how do I print the map's values instead?

ben3000
  • 4,629
  • 6
  • 24
  • 43
Все Едно
  • 746
  • 3
  • 10
  • 24

3 Answers3

17

Use entrySet() (or values() if that's what you need) instead of keySet():

Map<String, Double> missions = new HashMap<>();
missions.put("name", 1.0);
missions.put("name1", 2.0);
missions.entrySet().stream().forEach(e-> System.out.println(e));
syntagma
  • 23,346
  • 16
  • 78
  • 134
  • 3
    You could pass the method reference directely instead of creating a lambda: `forEach(System.out::println)`. However, it's just a matter of style. – beatngu13 May 24 '17 at 21:09
  • 1
    Yes but in this case I am not sure if what OP wants is value or entry - if it's the latter, then lambda would be a better choice (as you may want to get key or value from an `Entry`). – syntagma May 24 '17 at 21:10
  • ty, how do you remember the stream api commads so well, i cant seem to get the logic behind methods it uses, its like learning a new languege lol – Все Едно May 24 '17 at 21:11
  • 1
    I just understand the logic behind it. It's also consistent with existing Java APIs. – syntagma May 24 '17 at 21:12
  • 3
    Also, it is better practice to [program to an interface](https://stackoverflow.com/questions/383947/what-does-it-mean-to-program-to-an-interface), like `Map missions = new HashMap<>();` – dumbPotato21 May 24 '17 at 21:13
  • 1
    @ΔλЛ IDK, keys => `keySet()`, values => `values()`, both => `entrySet()`; doesn't affect the `forEach`. But as I said, it's a style thing—just wanted to mention it. – beatngu13 May 24 '17 at 21:17
3
HashMap<String, Double> missions = new HashMap<>();
missions.put("name", 1.0);
missions.put("name1", 2.0);
missions.entrySet().forEach(System.out::println);

Output:

name=1.0
name1=2.0
sureshhewabi
  • 91
  • 11
  • 100% agree with you. What I thought was, since question is already answered, my answer will help to a person who is looking for a solution can easily locate the answer. But I do agree with you which I learnt something from you, thanks. – sureshhewabi Feb 01 '19 at 16:48
-1
// Stores the values in a list which can later used

missions.values().stream().collect(Collectors.toList());

or

//print it to standard op

missions.values().forEach(val -> System.out.println(val));
Ameya
  • 17
  • 4
  • 4
    Please read [answer] and refrain from answering code-only. Instead, remember you are not only answering the OP, but also to any future readers (especially when answering 3 year old question). Thus, please [edit] the answer to contain an explanation as to **why** this code works. – Adriaan Jun 04 '20 at 14:36