如何将 Stream<Stream<String>> 转换为 List?

How to convert Stream<Stream<String>> to List?

我这里有一些代码:

public class MapAndFlatMap {

public static Stream<String> letters(String s) {
    List<String> result = new ArrayList<>();
    for (int i = 0; i < s.length(); i++)
        result.add(s.substring(i, i + 1));
    return result.stream();
}

public static void main(String[] args) {
    List<String> words = Arrays.asList("BOAT", "LORRY");

    Stream<String> lowercaseWords = words.stream().map(String::toLowerCase);
    List<String> result = lowercaseWords.collect(Collectors.toList());
    System.out.println(result);

    Stream<String> firstLetters = words.stream().map(s -> s.substring(0, 1));
    result = firstLetters.collect(Collectors.toList());
    System.out.println(result);

    Stream<String> func2 = words.stream().flatMap(w -> letters(w));
    result = func2.collect(Collectors.toList());
    System.out.println(result);

    Stream<Stream<String>> func = words.stream().map(w -> letters(w));

}

}

问题是我不知道如何将 Stream<Stream<String>> func = words.stream().map(w -> letters(w)); 转换为 List 以将其直接显示在控制台中,就像我在前面的示例中所做的那样。

如果你想结束一个List<String>:

List<String> singleListResult = words.stream()
                               .flatMap(w -> letters(w)) //result:  Stream<String>
                               .collect(Collectors.toList());

如果你想要 List<List<String>>:

List<List<String>> nestedList= words.stream()
                               .map(w -> letters(w).collect(Collectors.toList())) //result: Stream<List<String>> 
                               .collect(Collectors.toList());

下面的也对你有帮助,

        List<String> words = Arrays.asList("BOAT", "LORRY");

        List<String> collect = words.stream()
                                    .map(s -> s.codePoints()
                                               .mapToObj(a -> String.valueOf((char)a))
                                               .collect(Collectors.joining(",")))
                                    .collect(Collectors.toList());
        System.out.println("output = " + collect);

您不需要 letters 方法来获取单个流中单词的字母。

  • String.split("") - 将创建字符串的字母数组。
  • Arrays.stream() - 将流式传输该数组。
  • flatMap 会将所有这些流合并为一个。
List<String> list =
        words.stream().flatMap(a -> Arrays.stream(a.split("")))
                .collect(Collectors.toList());

System.out.println(list);

版画

[B, O, A, T, L, O, R, R, Y]