连接流行前,再进行收集。

huangapple go评论67阅读模式
英文:

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”这个术语,我有点陌生,所以任何建议都将不胜感激。

更新:假设我想将上面代码中的流映射为只包含01int[]数组,实际上,我尝试了下面的代码,它运行良好,但似乎效率不高,而且需要规范化。

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&lt;String&gt; binText = &quot;hello&quot;.chars()
    .mapToObj(x-&gt; Integer.toBinaryString(x))
    .map(x-&gt; String.format(&quot;%8s&quot;, x).replaceAll(&quot; &quot;, &quot;0&quot;));

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 = &quot;hello&quot;.chars()
                     .mapToObj(x-&gt; Integer.toBinaryString(x))
                     .map(x-&gt; String.format(&quot;%8s&quot;, x).replaceAll(&quot; &quot;, &quot;0&quot;))
                     .flatMap(s-&gt; Stream.of(s.split(&quot;&quot;)))
                     .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 = &quot;hello&quot;.chars()
        .mapToObj(Integer::toBinaryString)
        .map(x-&gt; String.format(&quot;%8s&quot;, x).replace(&quot; &quot;, &quot;0&quot;))
        .collect(Collectors.joining());

huangapple
  • 本文由 发表于 2020年10月16日 00:28:41
  • 转载请务必保留本文链接:https://go.coder-hub.com/64375929.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定