繁体   English   中英

Java Stream数字到数字

[英]Java Stream digits to number

我正在努力为此获得一个正常运行的代码。 我有一个0到9之间的数字流。我想从这些数字中得到一个BigInteger 例:

IntStream digits = IntStream.of(1, 2, 3) // should get me a Biginteger 123.
IntStream digits = IntStream.of(9, 5, 3) // should get me a Biginteger 953.

有没有办法连接流中的所有元素? 这是我的基本想法:

digits.forEach(element -> result=result.concat(result, element.toString()));

您可以将每个数字映射到一个字符串,将它们连接在一起,然后从中创建一个BigInteger

BigInteger result =
    IntStream.of(1, 2, 3)
             .mapToObj(String::valueOf)
             .collect(Collectors.collectingAndThen(Collectors.joining(), 
                                                    BigInteger::new));

你可以减少如下:

BigInteger big1 = IntStream.of(1, 2, 3, 4, 5, 6, 7, 8, 9)
    .mapToObj(BigInteger::valueOf)
    .sequential() // if parallel, reduce would return sweet potatoes
    .reduce((a, b) -> a.multiply(BigInteger.TEN).add(b))
    .orElse(BigInteger.ZERO);

System.out.println(big1); // 123456789

虽然我认为创建一个String并将其用作BigInteger构造函数的参数会更好,就像@Mureinik的回答一样。 这里我使用的变量不会为每个数字创建一个String对象:

String digits = IntStream.of(1, 2, 3, 4, 5, 6, 7, 8, 9)
    .collect(StringBuilder::new, StringBuilder::append, StringBuilder::append)
    .toString();
BigInteger big2 = new BigInteger(digits);

System.out.println(big2); // 123456789

你没有做那么糟糕,我建议使用forEachOrdered小改动,因为forEach不保证并行流的顺序和StringBuilder集合。 就像是:

IntStream digits = IntStream.of(1, 2, 3);
StringBuilder sb = new StringBuilder();
digits.forEachOrdered(sb::append);
System.out.println(new BigInteger(sb.toString()));

这是StreamEx的解决方案

BigInteger res = new BigInteger(IntStreamEx.of(1, 2, 3).joining(""));

或者我们应该删除前缀'0',如果可能的话

BigInteger res = new BigInteger(IntStreamEx.of(0, 1, 2).dropWhile(i -> i == 0).joining(""));

也许我们应该添加空流检查:

String str = IntStreamEx.of(0, 1, 2).dropWhile(i -> i == 0).joining("")
BigInteger res = str.length() == 0 ? BigInteger.ZERO : new BigInteger(str);

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM