IntStream of chars to Strings - Java

2020-06-30 05:28发布

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

3条回答
聊天终结者
2楼-- · 2020-06-30 06:19

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);
查看更多
beautiful°
3楼-- · 2020-06-30 06:21

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.

查看更多
太酷不给撩
4楼-- · 2020-06-30 06:34

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);
查看更多
登录 后发表回答