簡體   English   中英

如何使用流計算列表的總和?

[英]How to calculate the sum of the list using stream?

我有一個List<Integer>{ 1, 2, 3 ,4, 5 } ,我想得到像12345的結果。

如何使用Java8流任何智能方式執行此操作?

List由單個數字的非負整數組成。

我絕對可以做到1*10000+ 2 * 1000 + 3*100 + 4*10 + 5 ,但這很乏味。

使用IntStream.reduce

int n = IntStream.of(array).reduce(0, (a,b) -> 10*a + b)

這實際上與:

int n = 0;
for (int b : array) {
  n = 10 * n + b;
}

就個人而言,我會在沒有其他約束的情況下選擇后者,因為它更簡單的代碼,不涉及相對重量級的流框架,更容易調試等。

這個是不使用流,但使用正則表達式的可能方式

Integer.parseInt(Arrays.toString(nums).replaceAll("\\D+", ""));

您還可以使用以下方法獲得相同的結果:

List<Integer> ints = Arrays.asList(1, 2, 3, 4, 5);
int size = ints.size();
double res = IntStream.range(1, size + 1)
        .mapToDouble(i -> ints.get(i - 1) * Math.pow(10, size - i))
        .sum();

這只是添加每個digit*(10^digit_position_from_right)的總和,而digit_position_from_right從零開始。

也許,最實用的想法之一是將數字視為字符串,然后在最后解析它們:

List<Integer> list = Arrays.asList(1, 2, 3, 4, 5);
Long result = list.stream()
  .map(Object::toString)
  .collect(Collectors.collectingAndThen(
    Collectors.joining(), Long::parseLong));

結果可以使用以下方法實現:

List<Integer> nums = Arrays.asList(1, 2,3,4);
String s = "";
for (Integer x : nums) {
     s += x.toString();
}
Integer FinalNum = Integer.parseInt(s);

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM