1

I have following situation. (pseudocode)

class A {
  id;
  List<B> bs;
}

class B {}

I wonder how to convert List os As -> Map of Bs

List<A> as;

// the Map key is A.id (Map<A.id, List<B>>)
Map<Integer, List<B>> bs = as.stream()
                       .map(a ->a.getBs())
                       .collect(// I dont know what to add here ???);
4
  • 2
    Map<Integer, B> or Map<Integer, List<B>> ? Commented Oct 31, 2017 at 7:59
  • what are you going to do with the few values for one key? Commented Oct 31, 2017 at 8:00
  • sorry I meant Map<Integer, List<B>>, (corrected) Commented Oct 31, 2017 at 8:04
  • Here i have given a lot of examples for that. You may find it useful for your question javagists.com/java-8-streams-list-to-map-examples Commented Oct 31, 2017 at 8:07

1 Answer 1

3

Seems like you want sometime like this:

 Map<Integer, List<B>> bs = as.stream()
        .collect(Collectors.toMap(A::getId, A::getBs));
Sign up to request clarification or add additional context in comments.

4 Comments

Assuming id is unique...
@shmosel agree...
My interpretation was that OP wanted to group and flatten multiple bs, but I could be wrong.
@shmosel Indeed, the initial question context that was and the question title still fall in the line of intuition there.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.