Chetan Robbin :
Map.Entry::getKey
is throwing error for the below code
Map<String,List <String> > bikes= new HashMap<>();
bikes.put("ROBBIN",Arrays.asList("FZ","APACHE","HONDA"));
bikes.put("VIN",Arrays.asList("FZ","HONDA"));
bikes.put("GRACE",Arrays.asList("APACHE","HONDA"));
bikes.put("RUBBY",Arrays.asList("FZ","BUS","HONDA"));
Map<String, List<String>> group1;
bikes.entrySet().stream()
.flatMap(x->x.getValue().stream())
.collect(Collectors.groupingBy(
Function.identity(),
Collectors.mapping(Map.Entry::getKey,
Collectors.toList())
));
Eran :
flatMap(x->x.getValue().stream())
converts your Stream<Map.Entry<String,List <String>>>
to a Stream<String>
, so you don't have Map.Entry
s anymore.
It looks like you want to invert the input Map
(i.e. make the List
elements of the values of the input Map
the keys of the output Map
).
This can be done as follows:
Map<String, List<String>> group1 =
bikes.entrySet()
.stream().flatMap(e->e.getValue()
.stream()
.map(v->new SimpleEntry<String,String>(v,e.getKey())))
.collect(Collectors.groupingBy(Map.Entry::getKey,
Collectors.mapping(Map.Entry::getValue,
Collectors.toList())));
Now flatMap
transforms each Map.Entry<String,List<String>>
to multiple Map.Entry<String,String>
instances, each comprised of a key which is a value of the List<String>
and a value which is the key of the original Map.Entry
.
This will result in the following Map
:
{BUS=[RUBBY], FZ=[ROBBIN, VIN, RUBBY], APACHE=[GRACE, ROBBIN], HONDA=[GRACE, ROBBIN, VIN, RUBBY]}
Guess you like
Origin http://43.154.161.224:23101/article/api/json?id=328414&siteId=1