Quantcast
Channel: Baeldung
Viewing all articles
Browse latest Browse all 3525

Finding Max/Min of a List or Collection

$
0
0

1. Introduction

A quick intro on how to find the min/max value from a given list/collection with the powerful Stream API in Java8.

2. Find Max in a List of Integers

We can use max() method provided through the java.util.Stream interface. It accepts a method reference:

@Test
public void whenListIsOfIntegerThenMaxCanBeDoneUsingIntegerComparator() {
    // given
    List<Integer> listOfIntegers = Arrays.asList(1, 2, 3, 4, 56, 7, 89, 10);
    Integer expectedResult = 89;

    // then
    Integer max = listOfIntegers
      .stream()
      .mapToInt(v -> v)
      .max().orElseThrow(NoSuchElementException::new);

    assertEquals("Should be 89", expectedResult, max);
}

Let’s take a closer look at the code:

  1. Calling stream() method on the list to get a stream of values from the list
  2. Calling mapToInt(value -> value) on the stream to get an Integer Stream
  3. Calling max() method on the stream to get the max value
  4. Calling orElseThrow() to throw an exception if no value is received from max()

3. Find Min with Custom Objects

In order to find the min/max on custom objects, we can also provide a lambda expression for our preferred sorting logic.

Let’s first define the custom POJO:

class Person {
    String name;
    Integer age;
      
    // standard constructors, getters and setters
}

We want to find the Person object with the minimum age:

@Test
public void whenListIsOfPersonObjectThenMinCanBeDoneUsingCustomComparatorThroughLambda() {
    // given
    Person alex = new Person("Alex", 23);
    Person john = new Person("John", 40);
    Person peter = new Person("Peter", 32);
    List<Person> people = Arrays.asList(alex, john, peter);

    // then
    Person minByAge = people
      .stream()
      .min(Comparator.comparing(Person::getAge))
      .orElseThrow(NoSuchElementException::new);

    assertEquals("Should be Alex", alex, minByAge);
}

Let’s have a look at this logic:

  1. Calling stream() method on the list to get a stream of values from the list
  2. Calling min() method on the stream to get the minimum value. We are passing a lambda function as a comparator, this is used to decide the sorting logic for deciding the minimum value
  3. Calling orElseThrow() to throw an exception if no value is received from min()

4. Conclusion

In this quick article, we explored how the max() and min() methods from Java 8’s Stream API can be used to find the maximum and minimum value from a List/Collection.

As always, the code is available over on Github.


Viewing all articles
Browse latest Browse all 3525

Trending Articles



<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>