Explain Codes LogoExplain Codes Logo

How to get maximum value from the Collection (for example ArrayList)?

java
collections
max-value
comparators
Nikita BarsukovbyNikita Barsukov·Sep 18, 2024
TLDR

Find the highest element in an ArrayList with the Collections.max().

int max = Collections.max(Arrays.asList(1, 2, 3));

This spits out max: 3. Remember to keep your list filled and ensure elements are Comparable. Otherwise, Java might throw a tantrum.

Nitty-gritty of maximum value retrieval

Custom comparators: For those who love control

In need of a made-to-order comparison? Go for a Comparator:

ArrayList<MyObject> myObjects = getMyObjects(); //might not contain your favorite object MyObject maxObject = Collections.max(myObjects, new MyComparator());

Or make it slick with Lambda expression:

MyObject maxObject = Collections.max(myObjects, Comparator.comparing(MyObject::getValue)); //smooth as butter

Embrace modernity with Stream API

The Stream API aligns with the trend and keeps your code elegant:

OptionalInt maxValue = list.stream().mapToInt(v -> v).max(); maxValue.ifPresent(max -> System.out.println("Stream Max: " + max)); // prints only if present, else stays quiet.

OptionalInt takes care of the empty streams like a charm.

Edge cases and performance: They matter too!

Working with a big data? Understand your requirements:

  • A direct loop might be faster but verbose.
  • Streams offer superior readability but come at a cost (They aren't high maintanence though 😄).

No elements? No problems!

Working with empty collections? Here's a preventive check:

if (!collection.isEmpty()) { //It's not about the quantity, it's about the quality! int max = Collections.max(collection); }

When you need creativity over Collections.max()

Hang on! Collections.max() doesn't give you all?

  • Have a custom loop for your specific needs.
  • Use Streams when you seek concise and creative max extraction.

Complementary min retrieval, just because we're awesome!

As a bonus, here's how you find minimum:

int min = Collections.min(Arrays.asList(1, 2, 3)); //Because opposites attract!