Finding Min/Max in an Array with Java – 用Java查找数组中的最小/最大值

最后修改: 2018年 4月 12日

中文/混合/英文(键盘快捷键:t)

1. Introduction

1.介绍

In this short tutorial, we’re going to see how to find the maximum and the minimum values in an array, using Java 8’s Stream API.

在这个简短的教程中,我们将看到如何使用Java 8的Stream API查找数组中的最大值和最小值。

We’ll start by finding the minimum in an array of integers, and then we’ll find the maximum in an array of objects.

我们先在一个整数数组中找到最小值,然后再在一个对象数组中找到最大值。

2. Overview

2.概述

There are many ways of finding the min or max value in an unordered array, and they all look something like:

在无序数组中寻找最小或最大值的方法有很多,它们看起来都差不多。

SET MAX to array[0]
FOR i = 1 to array length - 1
  IF array[i] > MAX THEN
    SET MAX to array[i]
  ENDIF
ENDFOR

We’re going to look at how Java 8 can hide these details from us. But, in cases where Java’s API doesn’t suit us, we can always go back to this basic algorithm.

我们要看一下Java 8如何向我们隐藏这些细节。但是,在Java的API不适合我们的情况下,我们总是可以回到这个基本算法。

Because we need to check each value in the array, all implementations are O(n).

因为我们需要检查数组中的每个值,所有的实现都是O(n)

3. Finding the Smallest Value

3.寻找最小的价值

The java.util.stream.IntStream interface provides the min method that will work just fine for our purposes.

java.util.stream.IntStream接口提供了min方法,对于我们的目的来说,这个方法可以很好地工作。

As we are only working with integers, min doesn’t require a Comparator:

由于我们只处理整数,min不需要一个Comparator

@Test
public void whenArrayIsOfIntegerThenMinUsesIntegerComparator() {
    int[] integers = new int[] { 20, 98, 12, 7, 35 };
    
    int min = Arrays.stream(integers)
      .min()
      .getAsInt();

    assertEquals(7, min);
}

Notice how we created the Integer stream object using the stream static method in Arrays. There are equivalent stream methods for each primitive array type.

注意我们是如何使用Arrays中的stream静态方法创建Integer流对象的。每个原始数组类型都有相应的stream方法。

Since the array could be empty, min returns an Optional, so to convert that to an int, we use getAsInt.

由于数组可能是空的,min返回一个Optional,所以为了将其转换成int,我们使用getAsInt

4. Finding the Largest Custom Object

4.寻找最大的自定义对象

Let’s create a simple POJO:

让我们创建一个简单的POJO。

public class Car {
    private String model;
    private int topSpeed;

    // standard constructors, getters and setters
}

And then we can use the Stream API again to find the fastest car in an array of Cars:

然后我们可以再次使用StreamAPI,在一个Cars的数组中找到最快的汽车。

@Test
public void whenArrayIsOfCustomTypeThenMaxUsesCustomComparator() {
    Car porsche = new Car("Porsche 959", 319);
    Car ferrari = new Car("Ferrari 288 GTO", 303);
    Car bugatti = new Car("Bugatti Veyron 16.4 Super Sport", 415);
    Car mcLaren = new Car("McLaren F1", 355);
    Car[] fastCars = { porsche, ferrari, bugatti, mcLaren };

    Car maxBySpeed = Arrays.stream(fastCars)
      .max(Comparator.comparing(Car::getTopSpeed))
      .orElseThrow(NoSuchElementException::new);

    assertEquals(bugatti, maxBySpeed);
}

In this case, the static method stream of Arrays returns an instance of the interface java.util.stream.Stream<T> where the method max requires a Comparator.

在这种情况下,Arrays的静态方法stream返回一个接口java.util.stream.Stream<T>的实例,其中方法max需要一个Comparator

We could’ve constructed our own custom Comparator, but Comparator.comparing is much easier.

我们可以构建我们自己的自定义比较器,但是Comparator.comparing更容易。

Note again that max returns an Optional instance for the same reason as before.

再次注意,max会返回一个Optional实例,原因与之前相同。

We can either get this value, or we can do whatever else is possible with Optionals, like orElseThrow that throws an exception if max doesn’t return a value.

我们可以获取这个值,或者我们可以用Optionals做其他的事情,比如orseThrow,如果max没有返回一个值,就抛出一个异常。

5. Conclusion

5.结论

We saw in this short article how easy and compact it is to find max and min on an array, using the Stream API of Java 8.

在这篇短文中,我们看到了使用Java 8的Stream API在数组上查找最大值和最小值是多么简单和紧凑。

For more information on this library please refer to the Oracle documentation.

关于这个库的更多信息,请参考Oracle文档

The implementation of all these examples and code snippets can be found over on GitHub.

所有这些例子和代码片断的实现都可以在GitHub上找到over