IntStream of chars to Strings - Java

2020-06-30 05:33发布

问题:

Is it possible to convert stream of chars str.chars() to stream with Strings, where each String contains 5 characters, for example?

回答1:

I don't think trying to combine elements from the characters is a good fit for Java streams without using some third party libraries.

If you want a stream of 5 character substrings I would split them like this:

String s = "1234567890123456789012345678901234567890";
IntStream.range(0, s.length()/5)
        .mapToObj(i -> s.substring(i*5, (i+1)*5))
        .forEach(System.out::println);


回答2:

You can simply split you string into five character sized strings using

String[] split = string.split("(?<=\\G.{5})");

If it has to be using streams, you may use, e.g.

Pattern.compile("(?<=\\G.{5})").splitAsStream(string).forEach(System.out::println);


回答3:

Yes, it is possible if using a stateful lambda expression, but it is considered to be a bad practice.

One should be able to process the stream in serial or parallel. The order of the element processing would be different, but both should lead to the same result, which is possible only with stateless expressions.