How to get maximum value from the Collection (for example ArrayList)?
⚡TLDR
Find the highest element in an ArrayList
with the Collections.max()
.
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:
Or make it slick with Lambda expression:
Embrace modernity with Stream API
The Stream API aligns with the trend and keeps your code elegant:
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:
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:
Linked
Was this article helpful?