我想对一个整数列表求和。它的工作原理如下,但是语法感觉不太对。代码可以优化吗?

Map<String, Integer> integers;
integers.values().stream().mapToInt(i -> i).sum();

当前回答

可以使用reduce()对整数列表求和。

int sum = integers.values().stream().reduce(0, Integer::sum);

其他回答

不幸的是,看起来像流API只返回正常的流,从List<Integer># Stream()。我猜他们是被迫这么做的因为泛型的工作方式。

这些正常的流是泛型对象,所以没有专门的方法,如sum()等,所以你必须使用奇怪的重新流“看起来像一个无操作”转换默认情况下获得这些方法... .mapToInt(i -> i)。

另一种选择是使用“Eclipse Collections”,它就像一个扩展的java流API

IntLists.immutable.ofAll (integers.values ()) .sum ();

我已经声明了一个整数列表。

ArrayList<Integer> numberList = new ArrayList<Integer>(Arrays.asList(1, 2, 3, 4, 5));

你可以试试下面这些不同的方法。

使用mapToInt

int sum = numberList.stream().mapToInt(Integer::intValue).sum();

使用summarizingInt

int sum = numberList.stream().collect(Collectors.summarizingInt(Integer::intValue)).getSum();

使用减少

int sum = numberList.stream().reduce(Integer::sum).get().intValue();

希望这能帮助那些在清单上有物品的人。

如果您有一个对象列表,并且想要对该对象的特定字段求和,请使用下面的方法。

List<ResultSom> somList = MyUtil.getResultSom();
BigDecimal result= somList.stream().map(ResultSom::getNetto).reduce(
                                             BigDecimal.ZERO, BigDecimal::add);

可以使用reduce()对整数列表求和。

int sum = integers.values().stream().reduce(0, Integer::sum);
IntStream.of(1, 2, 23).sum();
IntStream.of(1, 2, 23,1, 2, 23,1, 2, 23).max().getAsInt();