英文:
Concat stream lines before collecting them
问题
下面的代码简单地生成了五行流,我需要将这些行连接成一行(在流中),以便在收集它们之前进一步使用。代码的目的是将一个字符字符串转换为一个长的二进制字符串。
Stream<String> binText = "hello".chars()
.mapToObj(x -> Integer.toBinaryString(x))
.map(x -> String.format("%8s", x).replaceAll(" ", "0"));
对于“Stream API”这个术语,我有点陌生,所以任何建议都将不胜感激。
更新:假设我想将上面代码中的流映射为只包含0
和1
的int[]
数组,实际上,我尝试了下面的代码,它运行良好,但似乎效率不高,而且需要规范化。
int[] binText = "hello".chars()
.mapToObj(x -> Integer.toBinaryString(x))
.map(x -> String.format("%8s", x).replaceAll(" ", "0"))
.flatMap(s -> Stream.of(s.split("")))
.mapToInt(Integer::parseInt)
.toArray();
是这样的吗?
英文:
Simply, the code below produces a stream of five lines, I need to concat these lines into one line (while streaming) for further use and before collecting them.The code is about to convert a character string into one long binary string
Stream<String> binText = "hello".chars()
.mapToObj(x-> Integer.toBinaryString(x))
.map(x-> String.format("%8s", x).replaceAll(" ", "0"));
I'm a bit new for the term of "Stream API", so any suggestion would be appreciated.
Update: Let say I want map the stream from the above code into int []
of 0
and 1
, actually, I tried the below code and it works fine but it seems not efficient and need to be normalized
int [] binText = "hello".chars()
.mapToObj(x-> Integer.toBinaryString(x))
.map(x-> String.format("%8s", x).replaceAll(" ", "0"))
.flatMap(s-> Stream.of(s.split("")))
.mapToInt(Integer::parseInt)
.toArray();
isn't it ?
答案1
得分: 1
你所寻找的是一个收集器,用于连接这些字符串,你可以使用:
.collect(Collectors.joining())
最终完整的解决方案可能是:
String binText = "hello".chars()
.mapToObj(Integer::toBinaryString)
.map(x-> String.format("%8s", x).replace(" ", "0"))
.collect(Collectors.joining());
英文:
What you are looking for is a collector to join those strings and you would have
.collect(Collectors.joining())
eventually the complete solution could be:
String binText = "hello".chars()
.mapToObj(Integer::toBinaryString)
.map(x-> String.format("%8s", x).replace(" ", "0"))
.collect(Collectors.joining());
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论