-3

I've got some code here:

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

}

}

The problem is that I don't have any idea how to convert Stream<Stream<String>> func = words.stream().map(w -> letters(w)); to List to display it right into the console as I did with previous examples.

DePi
  • 3
  • 2

3 Answers3

1

If you want to end up with a single List<String>:

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

If you want a List<List<String>>:

List<List<String>> nestedList= words.stream()
                               .map(w -> letters(w).collect(Collectors.toList())) //result: Stream<List<String>> 
                               .collect(Collectors.toList());
Beri
  • 11,470
  • 4
  • 35
  • 57
0

The below also helps you,

        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);
prostý člověk
  • 909
  • 11
  • 29
0

You don't need a letters method to get the letters of the words in a single stream.

  • String.split("") - will create an array of letters of the string.
  • Arrays.stream() - will stream that array.
  • flatMap will flatten all those streams into one.
List<String> list =
        words.stream().flatMap(a -> Arrays.stream(a.split("")))
                .collect(Collectors.toList());

System.out.println(list);

Prints

[B, O, A, T, L, O, R, R, Y]
WJS
  • 36,363
  • 4
  • 24
  • 39
  • 1
    I needed that method because I'm currently reading a book, where this example took place. That's why I wanted to figure out how to do it. But thanks for another explanation<3 – DePi Nov 11 '20 at 16:22