Hashmap with Streams in Java 8 Streams to collect value of Map
What you need to do is create a Stream
out of the Map
's .entrySet()
:
// Map<K, V> --> Set<Map.Entry<K, V>> --> Stream<Map.Entry<K, V>>
map.entrySet().stream()
From the on, you can .filter()
over these entries. For instance:
// Stream<Map.Entry<K, V>> --> Stream<Map.Entry<K, V>>
.filter(entry -> entry.getKey() == 1)
And to obtain the values from it you .map()
:
// Stream<Map.Entry<K, V>> --> Stream<V>
.map(Map.Entry::getValue)
Finally, you need to collect into a List
:
// Stream<V> --> List<V>
.collect(Collectors.toList())
If you have only one entry, use this instead (NOTE: this code assumes that there is a value; otherwise, use .orElse()
; see the javadoc of Optional
for more details):
// Stream<V> --> Optional<V> --> V
.findFirst().get()
For your Q2, there are already answers to your question. For your Q1, and more generally when you know that the key's filtering should give a unique value, there's no need to use Streams at all.
Just use get
or getOrDefault
, i.e:
List<String> list1 = id1.getOrDefault(1, Collections.emptyList());
If you are sure you are going to get at most a single element that passed the filter (which is guaranteed by your filter), you can use findFirst
:
Optional<List> o = id1.entrySet()
.stream()
.filter( e -> e.getKey() == 1)
.map(Map.Entry::getValue)
.findFirst();
In the general case, if the filter may match multiple Lists, you can collect them to a List of Lists :
List<List> list = id1.entrySet()
.stream()
.filter(.. some predicate...)
.map(Map.Entry::getValue)
.collect(Collectors.toList());