How to split a String into a Stream of Strings?

前端 未结 3 1211
北恋
北恋 2020-12-08 00:04

What is the best method of splitting a String into a Stream?

I saw these variations:

  1. Arrays.stream(\"b,l,a\".split(\",\"))
3条回答
  •  悲&欢浪女
    2020-12-08 00:28

    Arrays.stream/String.split

    Since String.split returns an array String[], I always recommend Arrays.stream as the canonical idiom for streaming over an array.

    String input = "dog,cat,bird";
    Stream 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.

    Stream stream = Stream.of(input.split(","));     // works, but is non-idiomatic
    Stream stream = Stream.of("dog", "cat", "bird"); // intended use case
    

    Pattern.splitAsStream

    Pattern.compile(",").splitAsStream(string) has the advantage of streaming directly rather than creating an intermediate array. So for a large number of sub-strings, this can have a performance benefit. On the other hand, if the delimiter is trivial, i.e. a single literal character, the String.split implementation will go through a fast path instead of using the regex engine. So in this case, the answer is not trivial.

    Stream stream = Pattern.compile(",").splitAsStream(input);
    

    If the streaming happens inside another stream, e.g. .flatMap(Pattern.compile(pattern) ::splitAsStream) there is the advantage that the pattern has to be analyzed only once, rather than for every string of the outer stream.

    Stream stream = Stream.of("a,b", "c,d,e", "f", "g,h,i,j")
        .flatMap(Pattern.compile(",")::splitAsStream);
    

    This is a property of method references of the form expression::name, which will evaluate the expression and capture the result when creating the instance of the functional interface, as explained in What is the equivalent lambda expression for System.out::println and java.lang.NullPointerException is thrown using a method-reference but not a lambda expression

提交回复
热议问题