3

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

Daniel Taub
  • 5,133
  • 7
  • 42
  • 72
user3100209
  • 357
  • 1
  • 4
  • 17
  • What have you tried? What is your question, other than "write my code for me"? Did you try a search on this site: https://stackoverflow.com/q/25903137/1531971 –  Jan 16 '18 at 16:52
  • I tried it but I can't seem to do the nested part of it ... heres what I have. stream().map(groups -> groups.getGroupIds()) .flatMap(group -> groups.stream()).collect(Collectors.toList()); – user3100209 Jan 16 '18 at 16:55
  • 2
    Comments can be removed. Put relevant details in the question itself. And tell us what you have tried, even referencing other SO Q&A. –  Jan 16 '18 at 16:56
  • 1
    please have a look at this question: https://stackoverflow.com/questions/40484985/flatten-a-mapinteger-liststring-to-mapstring-integer-with-stream-and-lam – Anton Balaniuc Jan 16 '18 at 17:30
  • Correct me if I am wrong. But the linked solution does not handle duplicate `groupId` which can possibly be the case with OP. – tsolakp Jan 16 '18 at 19:51
  • @tsolakp well the linked question does say `whereas toMap without a merger function will throw an exception...`, adding a merge Function is pretty straight-forward anyway – Eugene Jan 16 '18 at 20:14
  • @Eugene. Just wanted to make sure OP would realize that linked answer does not handle duplicates and will throw exception. – tsolakp Jan 16 '18 at 20:26

1 Answers1

4
 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.

Eugene
  • 117,005
  • 15
  • 201
  • 306