Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Nested Streams java 8 [duplicate]

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

like image 635
user3100209 Avatar asked Mar 23 '26 01:03

user3100209


1 Answers

 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.

like image 163
Eugene Avatar answered Mar 25 '26 12:03

Eugene



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!