Split list of words using streams in Java

java stream split string
java split list based on condition
java split list into sublists based on value
java stream map
java 8 split string
string> stream in java 8
java 8 stream sublist
java split list into chunks

I am having this method that takes a number of lists, which contain lines of books. I am combing them to a stream to then iterate over them to split on all non-letter's \\P{L}.

Is there a way to avoid the for-each loop and process this within a stream?

private List<String> getWordList(List<String>... lists) {
        List<String> wordList = new ArrayList<>();

        Stream<String> combinedStream = Stream.of(lists)
                .flatMap(Collection::stream);
        List<String> combinedLists = combinedStream.collect(Collectors.toList());

        for (String line: combinedLists) {
            wordList.addAll(Arrays.asList(line.split("\\P{L}")));
        }

        return wordList;
}

Having stream, you can simply "flatMap" further and return the result:

return combinedStream
        .flatMap(str -> Arrays.stream(str.split("\\P{L}")))
        .collect(Collectors.toList());

To put it altogether:

private List<String> getWordList(List<String>... lists) {
    return Stream.of(lists)
        .flatMap(Collection::stream)
        .flatMap(str -> Arrays.stream(str.split("\\P{L}")))
        .collect(Collectors.toList());
}

String Operations with Java and Stream API, Learn how to split a comma-separated String into a list of Strings and We'll also look at how to convert a string array to map using Stream API. String input = "dog,cat,bird"; Stream<String> stream = Arrays.stream(input.split( "," )); stream.forEach(System.out::println); Stream.of / String.split Stream.of is a varargs method which just happens to accept an array, due to the fact that varargs methods are implemented via arrays and there were compatibility concerns when varargs were introduced to Java and existing methods retrofitted to accept variable arguments.

You don't need to introduce so many variables :

private List<String> getWordList(List<String>... lists) {

    return Stream.of(lists) // Stream<Stream<String>>
                 .flatMap(Collection::stream) // Stream<String> 
                 .flatMap(Pattern.compile("\\P{L}")::splitAsStream) //Stream<String>     
                 .collect(toList()); // List<String>
}

As underlined by Holger, .flatMap(Pattern.compile("\\P{L}")::splitAsStream) should be favored over .flatMap(s -> Arrays.stream(s.split("\\P{L}"))) to spare array allocation and pattern compilation performed for each element of the stream.

Java, A quick article with many examples of joining and splitting arrays and collections using Java Stream API. 2. Join Two Arrays. Let's start by joining two Arrays together using Stream.concat: Next, let's split an array by the length of the words: Map<Integer, List<String>> result = Arrays.stream(animals). In this tutorial, leveraging the simple String.split function and the powerful Java 8 Stream, we illustrated how to join and split Arrays and Collections. You can find the code for this article over on GitHub.

You can combine all the list and flatMap for result

private List<String> getWordList(List<String>... lists) {
    return Stream.of(lists)
    .flatMap(Collection::stream)
    .flatMap(str -> Arrays.stream(str.split("\\P{L}")))
    .collect(Collectors.toList());
}

How to split string into stream in Java 8 by Example, //Spliting names by comma converting into stream. Stream<String> namesStream = pattern.splitAsStream(names);. //Iterate stream using forEach and Print the� How to split string into stream in Java 8 by Example in Streams - JAVA Complete Reference by Examples. How to filter an List stream using Lambda expression in

StringStreams.java, Fun with Java 8 pipelines/streams of strings * * @author Chris Bailey-Kellogg, a stream from list of words, filter and print those meeting filter List<String> words +"); // split on punctuation and white space Map<String, Long> wordCounts� Download Run Code. 2. List.subList() This is recommended approach in Java SE where we use List.subList() method that returns a view of this list between the specified indexes.

Convert comma-separated String to List in Java, From Java 8 onward, we can use Stream API. The idea is to split the string using split() method, convert the array into stream, and then collect all the input� You might think that it is easy; we can use Files.lines (), which you saw in the previous article, because it can return a stream consisting of the lines of a file. We can then split each line into words using a map () operation and, finally, use the operation distinct () to remove duplicates. A first attempt could be the code shown in Listing 4.

Java split string tutorial - splitting strings in Java, Java split string tutorial shows how to split strings in Java. We use String's split(), Pattern's splitAsStream() and Guava Splitter's on() methods. var output = names.split("-", 4); Arrays.stream(output).forEach(System.out::println);� Now, let's create a function, which would split a comma separated String into a list of String using Stream API: public static List<String> split(String str) { return Stream.of (str.split (",")).map (elem -> new String (elem))

Comments
  • As explained in this answer, it’s recommended to use .flatMap(Pattern.compile("\\P{L}") ::splitAsStream), this avoids recompiling the pattern for every stream element and does not populate a potentially large intermediate array.
  • @Holger Thank you very much for this reference. I didn't not still see this one from Java 8. But I don't like very much the method reference in this case (Pattern.splitAsStream(String) is not common to use for me at least) but according to your comment in the other post, it is required and I get it. We could also compile the pattern outside the stream but well not terrible either.
  • Well, you can also move the pattern to a constant like static final Pattern NON_LETTER_CHARS = Pattern.compile("\\P{L}"); and then use either .flatMap(NON_LETTER_CHARS::splitAsStream) or .flatMap(s -> NON_LETTER_CHARS.splitAsStream(s)). In the end, you also have to know about the regex engine when using s.split("\\P{L}").
  • Indeed That is that I referenced in my comment edit, sorry. It is a way but that it is not terrible either.
  • str is not a String here but a List. So List.split() cannot compile. You miss an intermediary operation : stackoverflow.com/a/54969149/270371