Combine collect of list with single value using streams

user8504707 :

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.

tobias_k :

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());

Guess you like

Origin http://10.200.1.11:23101/article/api/json?id=430106&siteId=1