I was reading about Guava's LinkedHashMultimap
and thought it might be useful to me.
I have a requirement such that I have a map as follows:
Key:Value
A B
A C
A D
P Q
P R
If above is the input in my map, then I want to use LinkedHashMultimap
to create a map like:
Key : Value
A List<B,C,D>
P List<Q,R>
Tried using LinkedHashMultimap
but it has following issue:
mapLen.entries().stream().forEach(entry -> {
System.out.println("mapTemp2 key + " + entry.getKey());
System.out.println("mapTemp2 value + " + entry.getValue());
});
Above prints the String
values in the map and not List<String>
.
Can someone pointout how it can be done.
(Kindly note: I am aware of normal core java solution of iterating, checking and the creating list and inserting into map.)
As we can see in javadoc, Multimap#entries()
returns Collection<Map.Entry<K,V>>
- so basically, you iterate over each key/value pair, instead of key/(value set). To do so, try turning Multimap<K, V>
to standard Map<K, List<V>>
. You can do that with Multimap#asMap()
, so your code would look like:
mapLen.asMap().entrySet().stream().forEach(entry -> {
System.out.println("mapTemp2 key + " + entry.getKey());
System.out.println("mapTemp2 value + " + entry.getValue());
});
PS. I guess you missed parenthesis after ...entries
- it's a method, not a property, so you should have used:
// vv DOWN HERE
mapLen.entries().stream().forEach(entry -> {
System.out.println("mapTemp2 key + " + entry.getKey());
System.out.println("mapTemp2 value + " + entry.getValue());
});