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
CodePudding user response:
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]
CodePudding user response:
Well, the difference with the linked question is that you have three levels: a sequence of Model
s, each model having multiple attributes. Those attributes are List
s, 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();