簡體   English   中英

使用流將列表的收集與單個值組合

[英]Combine collect of list with single value using streams

我有以下數據:

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

現在我想將這些數據收集到一個列表中,該列表包含CustomClass中的值和列表中的值。

我想得到這個: 1, 1, 2, 3, 5, 6, 7, 8

這是我實施的:

list.stream().forEach(item -> {
        result.add(item.value);
        item.values.stream().forEach(seconditem -> result.add(seconditem));
    });

我知道有一個收集方法的流,但我不明白如何使用它來收集同一個類的一個值和值列表。

您可以使用Stream.concat組合單個值的Stream.of和其他值的流:

List<Integer> result = list.stream()
        .flatMap(x -> Stream.concat(Stream.of(x.value), x.values.stream()))
        .collect(Collectors.toList());

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM