Finding Max/Min of a List or Collection – 寻找列表或集合的最大/最小值

最后修改: 2017年 2月 25日

1. Overview

1.概述

This tutorial is a quick intro on how to find the min and max values from a given list or collection with the powerful Stream API in Java 8.

本教程快速介绍了如何使用Java 8中强大的Stream API从给定的列表或集合中找到最小和最大值。

2. Find Max in a List of Integers

2.在一个整数列表中寻找最大值

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

我们可以使用通过java.util.Stream接口提供的max()方法,它接受一个方法引用。

@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

3.用自定义对象查找Min

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

为了找到自定义对象上的最小/最大值,我们也可以为我们喜欢的排序逻辑提供一个lambda表达式。

Let’s first define the custom POJO:

让我们首先定义自定义的POJO。

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

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

我们想找到具有最小年龄的Person对象。

@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 pass a lambda function as a comparator, and 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

4.结论

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

在这篇快速文章中,我们探讨了如何使用Java 8 Stream API中的max()min()方法来ListCollection中找到最大和最小值。

As always, the code is available over on GitHub.

像往常一样,代码可在GitHub上获得