0

Hello my question is very similar to Java8: Stream map two properties in the same stream but for some reason I cannot get my code to work.

So like that question, say I have a class Model

class Model {
    private List<Integer> listA;
    private List<Integer> listB;
    private List<Integer> listC;
    public List<Integer> getListA() {
        return listA;
    }

    public List<Integer> getListB() {
        return listB;
    }
    public List<Integer> getListC() {
        return listC;
    }
}

So I want to combine these lists from a List<Model> myList using a stream and my code looks like this:

myList.stream()
      .flatmap(i -> Stream.of(i.getListA(), i.getListB(), i.getListC()))
      .collect(Collectors.toList())
      .get(0)

But this approach ends up returning an empty list. I would appreaciate any suggestions

2 Answers 2

3

Well, the difference with the linked question is that you have three levels: a sequence of Models, each model having multiple attributes. Those attributes are Lists, so they as well may contain multiple elements.

Now you can use flatMap twice instead of once.

myList.stream()
    .flatMap(model -> Stream.of(model.getListA(), model.getListB(), model.getListC())
        .flatMap(List::stream))
    .toList();
Sign up to request clarification or add additional context in comments.

Comments

2

You must concatenate the 3 lists with Stream.concat. Once you've concatenated the streams (don't cross them!), flat map them to a Stream<Integer>, then collect to a List.

myList.stream()
      .flatMap(m -> Stream.concat(Stream.concat(m.getListA().stream(),
                                  m.getListB().stream()),
                    m.getListC().stream()))
      .collect(Collectors.toList());

With

List<Model> models = List.of(
    new Model(Arrays.asList(1, 2, 3), Arrays.asList(4, 5, 6), Arrays.asList(7, 8, 9)),
    new Model(Arrays.asList(11, 12, 13), Arrays.asList(14, 15, 16), Arrays.asList(17, 18, 19)),
    new Model(Arrays.asList(21, 22, 23), Arrays.asList(24, 25, 26), Arrays.asList(27, 28, 29))
);

The output is:

[1, 2, 3, 4, 5, 6, 7, 8, 9, 11, 12, 13, 14, 15, 16, 17, 18, 19, 21, 22, 23, 24, 25, 26, 27, 28, 29]

1 Comment

Thanks I really appreciate the help! Since I think Stream.concat only allows for 2 parameters, what I did was followed the example that they gave in the Stream.concat documentation for concatening multiple streams: Streams.of(e.getListA().stream(), .... ).flatMap(s->s).collect(...) and that fixed it

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.