Java流将数字转换为数字

3

我正在努力获取一个可以正常运行的代码。我有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()));
4个回答

4
您可以将每个数字映射到一个字符串,将它们全部连接起来,然后从中创建一个BigInteger
BigInteger result =
    IntStream.of(1, 2, 3)
             .mapToObj(String::valueOf)
             .collect(Collectors.collectingAndThen(Collectors.joining(), 
                                                    BigInteger::new));

看起来不错,也有意义,但我得到了“构造函数BigInteger(Object)未定义”的错误。另外,如果流中的数字超过9,我需要添加一个断言。但是,如果在此之前检查流则会关闭它,然后我就不能再使用它了。有什么想法? - Daniel Odesser

2
您可以按如下方式进行缩减:
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

2

你做得并不太糟,我建议你做一些微小的更改,例如使用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()));

1
这是使用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);

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接