Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java - summing list with filtering out lowest int

So, I have an int[] arr and want to sum it using streams while filtering out the minimum int. I have got a solution using two streams, which works but seems ineffective. Is there a way to do it with just one stream?

Code:

int min = Arrays.stream(arr)
                    .min()
                    .getAsInt();
int sum = Arrays.stream(arr)
                       .filter(i -> i != min)
                       .sum();
like image 273
Ibrahim Avatar asked Feb 17 '26 21:02

Ibrahim


2 Answers

This code below using IntSummaryStatistics should do the trick.

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();
}

From docs of IntSummaryStatistics:

A state object for collecting statistics such as count, min, max, sum, and average.

...

This computes, in a single pass, the count of people, as well as the minimum, maximum, sum, and average of their number of dependents.

EDIT: In case you'd like to remove all elements which have min value:

    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);

or

    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);
like image 172
kkmazur Avatar answered Feb 20 '26 09:02

kkmazur


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

int sumExcludingMin = Arrays.stream(arr)
            .sorted()
            .skip(1)
            .reduce(0, Integer::sum); // or using lambda: reduce(0, (x,y) -> x+y)
                                      // or specialized reduction form: sum()

Here, the first parameter of reduce(), 0, the identity element is both an initial seed value for the reduction and a default result if there are no input elements.

Further Reading:

  • Summary of Package java.util.stream
like image 28
Minar Mahmud Avatar answered Feb 20 '26 11:02

Minar Mahmud



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!