可以使用stream.mapToObj执行多个语句

FSm*_*FSm 9 java-8 java-stream

是否可以在mapToObj方法中执行多个语句?.假设我想使用以下代码将字符串转换为二进制字符串:

 String str = "hello";
 String bin = str.chars()
                  .mapToObj(x-> Integer.toBinaryString(x))
                  .collect(Collectors.joining(" "));
Run Code Online (Sandbox Code Playgroud)

但是,我想使用类似的东西处理前导零

String.format("%8s", x).replaceAll(" ", "0")
Run Code Online (Sandbox Code Playgroud)

那么,如何在mapToObj方法中添加它.我是Java 8新功能的新手.任何帮助,将不胜感激

Eug*_*ene 6

.mapToObj(x-> {
    String s = Integer.toBinaryString(x);
    s = String.format("%8s", s).replaceAll(" ", "0");
    return s;
 })
Run Code Online (Sandbox Code Playgroud)


Flo*_*own 6

您可以使用BigInteger并替换空间填充,而不是在格式化步骤中添加"0".这是有效的,因为BigInteger它被视为整体.

String bin = str.chars()
        .mapToObj(Integer::toBinaryString)
        .map(BigInteger::new)
        .map(x -> String.format("%08d", x))
        .collect(Collectors.joining(" "));
Run Code Online (Sandbox Code Playgroud)

编辑

正如@Holger建议使用更轻量级的解决方案long代替BigInteger,因为二进制表示Character.MAX_VALUE不超过限制long.

String bin = str.chars()
        .mapToObj(Integer::toBinaryString)
        .mapToLong(Long::parseLong)
        .mapToObj(l -> String.format("%08d", l))
        .collect(Collectors.joining(" "));
Run Code Online (Sandbox Code Playgroud)

  • 一个`long`已足以保存最大变换的`char`值,所以你可以使用`chars().mapToObj(Integer :: toBinaryString).mapToLong(Long :: parseLong).mapToObj(x - > String.format ("%08d",x))`.或者内联:`.chars().mapToObj(x - > String.format("%08d",Long.parseLong(Integer.toBinaryString(x)))).collect(Collectors.joining(""))`当然,如果格式化API支持二进制表示,则会更容易. (4认同)