Reputation:
I have the following data:
CustomClass first = new CustomClass(1, Arrays.asList(1, 2, 3));
CustomClass second = new CustomClass(5, Arrays.asList(6,7,8));
List<CustomClass> list = Arrays.asList(first, second);
Now I want to collect this data into a list that contains the value from CustomClass
and values from its list.
I want to obtain this: 1, 1, 2, 3, 5, 6, 7, 8
This is what I implemented:
list.stream().forEach(item -> {
result.add(item.value);
item.values.stream().forEach(seconditem -> result.add(seconditem));
});
I know there's a collect method for stream, but I don't understand how to use it to collect both one value and the list of values from the same class.
Upvotes: 17
Views: 2302
Reputation: 82899
You can use Stream.concat
to combine a Stream.of
the single value and the stream of the other values:
List<Integer> result = list.stream()
.flatMap(x -> Stream.concat(Stream.of(x.value), x.values.stream()))
.collect(Collectors.toList());
Upvotes: 22