Start learning free

LESSON 269 OF 671 · RECORDS, SORTING & BUILT-INS

Min, Max and Sum in Java

Lesson

TL ; DR:

Collections.min(list) gives the smallest value of a list.

Collections.max(list) gives the largest value.

A stream adds all the values up.


List<Integer> prices = new ArrayList<>(List.of(4, 9, 2, 7));

System.out.println(Collections.min(prices));    // 2

System.out.println(Collections.max(prices));    // 9

int total = prices.stream().mapToInt(x -> x).sum();

System.out.println(total);                      // 22


Full lesson:

In Maximum Number In Array, a loop found the largest value. In Sum of Numbers, a loop added numbers up. These jobs come up all the time. Java has ready-made methods for them.

  • Collections.min(list) gives the smallest value of the list.
  • Collections.max(list) gives the largest value.
  • list.stream().mapToInt(x -> x).sum() adds all the values up.

The sum uses a stream, as in Map and Filter. The call mapToInt(x -> x) turns each Integer into a plain int. Then sum() adds them.

Math.max(a, b) from Maximum Number In Array compares two values. Collections.max looks at a whole list.

Collections.min takes a list, like an ArrayList. It doesn't take an int[] array.

Watch out for an empty list. Collections.min and Collections.max throw a NoSuchElementException on it. An empty list has no smallest value. Check list.isEmpty() first. The stream's sum() of an empty list is 0.


Your task

minutes holds how many minutes you practiced coding on each day of a week.

Store the shortest day in shortest and the longest day in longest. Store the week's total in total.

Use the built-ins from this lesson. The code at the bottom prints all three.

Expected output:

shortest = 15
longest = 60
total = 235
STEP 1 OF 3
    Ctrl + Enter to check