Trying to use Java 8 Streams for this
HashMap<String,Games> groupGames = new HashMap<String,Games> ();
for(Groups group: groups){
for(int groupId : group.getGroupId){
groupGames.put(groupId, group.getGame());
}
}
This works fine but I want to use java 8 stream to achieve this same functionality.
This is what I have for stream
public void toStream(List<Group> group){
group.stream().map(groups -> groups.getGroupIds())
.flatMap(group -> groups.stream()).collect(Collectors.toList());
}
I'm having hard time putting each of the groupId with the game in the hashmap...
I'm able to flatten out the list of groupIds
groups.stream()
.flatMap(x -> x.getGroupId().stream()
.map(y -> new AbstractMap.SimpleEntry<>(y, x.getGame())))
.collect(Collectors.toMap(Entry::getKey, Entry::getValue, (x, y) -> y));
If you know there will be no duplicates, you can drop the last argument in (x,y) -> y; or you can provide a merge function that you think would be appropriate.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With