我正在尝试删除 java 8 中的重复数字,包括引用数。例如,我有一个数组,其值类似于 (2,3,2,5)
所有数字 2 都应删除,数字应保留为 3 和 5。 所以预期的总和是 8。但是在我下面的代码中,它仍然得到 2。它确实删除了重复的数字,但仍然保留了数字引用。
这是我的代码。
List<Integer> clearedNumbers = numbers.stream().distinct().collect(Collectors.toList());
int sum = clearedNumbers.stream().mapToInt(Integer::intValue).sum();
我得到的总和是 10 而不是 8。
最佳答案
我会收集每个数字的计数,并且只对单打求和:
System.out.println(
Stream.of(2,3,2,5)
.collect(Collectors.groupingBy(Function.identity(), Collectors.counting()))
.entrySet()
.stream()
.filter(e -> e.getValue() == 1)
.mapToInt(Map.Entry::getKey)
.sum());
输出 8
关于java - Java 8 去除重复数字并求和,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48881023/