Java - 汇总列表并过滤掉最低的 int

Ibr*_*him 2 java java-stream

所以,我有一个 int[] arr 并且想在过滤掉最小 int 的同时使用流对其进行求和。我有一个使用两个流的解决方案,它有效但似乎无效。有没有办法只用一个流来做到这一点?

代码:

int min = Arrays.stream(arr)
                    .min()
                    .getAsInt();
int sum = Arrays.stream(arr)
                       .filter(i -> i != min)
                       .sum();
Run Code Online (Sandbox Code Playgroud)

小智 5

下面使用IntSummaryStatistics 的代码应该可以解决问题。

public static void main(String[] args) {
    int[] arr = {1, 2, 3, 4, 5, 6};
    IntSummaryStatistics stats = Arrays.stream(arr).summaryStatistics();
    int sum = (int) stats.getSum() - stats.getMin();
}
Run Code Online (Sandbox Code Playgroud)

来自 IntSummaryStatistics 的文档:

一个状态对象,用于收集计数、最小值、最大值、总和和平均值等统计信息。

...

这将在一次通过中计算人数,以及他们的受抚养人人数的最小值、最大值、总和和平均值。

编辑:如果您想删除所有具有最小值的元素:

    int[] arr = {1, 2, 3, 1, 1, 1};

    TreeMap<Integer, Integer> map = Arrays.stream(arr).boxed()
        .collect(toMap(
            v -> v,
            v -> 1,
            Integer::sum,
            TreeMap::new
        ));

    map.remove(map.firstKey());
    int sum = map.entrySet().stream().mapToInt(e -> e.getKey() * e.getValue()).sum();
    System.out.println(sum);
Run Code Online (Sandbox Code Playgroud)

或者

    List<Integer> list = Arrays.stream(arr).sorted().boxed().collect(toList());
    Integer min = list.get(0);
    int sum2 = list.stream().mapToInt(i -> i).dropWhile(min::equals).sum();
    System.out.println(sum2);
Run Code Online (Sandbox Code Playgroud)