将`IntStream`打印为`String`的最简单方法 [英] Simplest way to print an `IntStream` as a `String`

查看:107
本文介绍了将`IntStream`打印为`String`的最简单方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

使用Java-8,我可以轻松地将 String (或任何 CharSequence )视为 IntStream 使用 chars codePoints 方法。

  IntStream chars =Hello world。。codePoints(); 

然后我可以操纵流的内容

  IntStream stars = chars.map(c  - > c ==''?'':'*'); 

我一直在寻找一种打印结果的整洁方式,我甚至找不到简单的方法。如何将这个 int 的流放回一个可以打印的表单,就像我可以 String 。 / p>

从以上明星我希望打印

  ***** ****** 


解决方案

  String result =Hello world。 
.codePoints()
//。parallel()//为大字符串取消注释这一行
.map(c - > c ==''?'':'*')
.collect(StringBuilder :: new,
StringBuilder :: appendCodePoint,StringBuilder :: append)
.toString();

但是,Hello world。。replaceAll([^] ,*)更简单。并非一切都受益于lambdas。


With Java-8 I can easily treat a String (or any CharSequence) as an IntStream using either the chars or the codePoints method.

IntStream chars = "Hello world.".codePoints();

I can then manipulate the contents of the stream

IntStream stars = chars.map(c -> c == ' ' ? ' ': '*');

I have been hunting for a tidy way to print the results and I cant even find a simple way. How do I put this stream of ints back into a form that can be printed like I can a String.

From the above stars I hope to print

***** ******

解决方案

String result = "Hello world."
  .codePoints()
//.parallel()  // uncomment this line for large strings
  .map(c -> c == ' ' ? ' ': '*')
  .collect(StringBuilder::new,
           StringBuilder::appendCodePoint, StringBuilder::append)
  .toString();

But still, "Hello world.".replaceAll("[^ ]", "*") is simpler. Not everything benefits from lambdas.

这篇关于将`IntStream`打印为`String`的最简单方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆