Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Print HashMap Values with Stream api

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?

like image 777
Все Едно Avatar asked May 24 '17 21:05

Все Едно


People also ask

How do I print HashMap values?

Print HashMap Elements in Java This is the simplest way to print HashMap in Java. Just pass the reference of HashMap into the println() method, and it will print key-value pairs into the curly braces.

How print all keys in HashMap?

Printing All Keys and Values From the HashMap keys. forEach(key -> System. out. println(key));

How to sort HashMap by its keys and values using stream?

In this article, we will discuss how to sort HashMap by its Keys and Values using stream in Java 8 Prior to Java 8 release, we can sort HashMap either by its Keys or Values as explained in the below articles, With the release of Java 8, we can use sorted () method of Stream class by passing Comparator objects 1. Sorting HashMap by its Keys

How to print all keys of HashMap in Java?

The keySet method of the HashMap class returns a Set view containing all the keys of the HashMap. You can also use the System.out.println statement instead of using the for loop if you do not want to change the output format. //will print all keys in format [key1, key2...]

What is a hashmap in Java?

A HashMap is a subclass of AbstractMap class and it is used to store key & value pairs. Each key is mapped to a single value in the map and the keys are unique. It means we can insert a key only once in a map and duplicate keys are not allowed, but the value can be mapped to multiple keys.

How to print the elements of a stream in Java?

There are 3 ways to print the elements of a Stream in Java: Below are the three ways to print the Stream in detail: Stream forEach (Consumer action): This method performs an action for each element of the stream. Stream forEach (Consumer action) is a terminal operation i.e, it may traverse the stream to produce a result or a side-effect.


Video Answer


2 Answers

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));
like image 86
syntagma Avatar answered Nov 10 '22 20:11

syntagma


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
like image 41
sureshhewabi Avatar answered Nov 10 '22 19:11

sureshhewabi