Print HashMap Values with Stream api
Asked Answered
D

3

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?

Durwin answered 24/5, 2017 at 21:4 Comment(0)
S
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));
Semiliquid answered 24/5, 2017 at 21:7 Comment(6)
You could pass the method reference directely instead of creating a lambda: forEach(System.out::println). However, it's just a matter of style.Sheply
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).Semiliquid
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 lolUpstate
I just understand the logic behind it. It's also consistent with existing Java APIs.Semiliquid
Also, it is better practice to program to an interface, like Map<String, Double> missions = new HashMap<>();Waring
@ΔλЛ 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.Sheply
K
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
Kassi answered 1/2, 2019 at 16:9 Comment(1)
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.Kassi
F
-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));
Favor answered 4/6, 2020 at 14:31 Comment(1)
Please read How to 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.Lemke

© 2022 - 2024 — McMap. All rights reserved.