IntStream of chars to Strings - Java

本秂侑毒 提交于 2019-12-09 13:59:53

问题


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.



来源:https://stackoverflow.com/questions/33402423/intstream-of-chars-to-strings-java

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!