Java中常用的从数组和List中找最大值最小值的方法

通常我们会遇到这样的需求,从一个数组或者List中需要从中找到最大的值。
下面介绍3种常见方法:

1. 使用for循环逐个比较

这种方式最容易理解,但是代码行数偏多,需要自己实现比较的逻辑。

@Test
public void testByForEach(){
    // given
    List<Double> numList = new ArrayList<>();
    numList.add(22.8);
    numList.add(56.0);
    numList.add(15.9);
    numList.add(56.0);

    // then
    Double maxValue = numList.get(0);
    for(Double d : numList){
        if(d.compareTo(maxValue) > 0){
            maxValue = d;
        }
    }

    Assert.assertEquals(56.0, maxValue, 0.0);
}

2. 使用Collections工具类

第二种方式使用JDK自带的Collections工具类,拿来主义,避免造重复的轮子。
代码行数只有一行,简单实用。

@Test
public void testByCollections(){
    // given
    List<Double> numList = new ArrayList<>();
    numList.add(22.8);
    numList.add(56.0);
    numList.add(15.9);
    numList.add(56.0);

    // then
    Double maxValue = Collections.max(numList);

    // assert
    Assert.assertEquals(56.0, maxValue, 0.0);
}

如果比较的是一个数组
我们也可以用Arrays先转成List,然后再用Collections。

@Test
public void testByArraysAndCollections(){
    // given
    Double[] numArr = new Double[]{22.8, 56.0, 15.9, 56.0};
    List<Double> numList = Arrays.asList(numArr);

    // then
    Double maxValue = Collections.max(numList);

    // assert
    Assert.assertEquals(56.0, maxValue, 0.0);
}

3. 使用Stream API

除了用工具类Collections,我们还可以用Java 8自带的Stream API来找最大值。

@Test
public void testByStream(){
    // given
    Double[] numArr = new Double[]{22.8, 56.0, 15.9, 56.0};
    List<Double> numList = Arrays.asList(numArr);

    // then
    Double maxValue = numList.stream() // list转stream
            .mapToDouble(d -> d)       // 把stream转成Double Stream
            .max()                     // 在Double Stream中找最大值
            .orElseThrow(NoSuchElementException::new); // 如果找不到最大值抛异常

    // assert
    Assert.assertEquals(56.0, maxValue, 0.0);
}

如果只是保存数值的数组或List,直接用Collections就简单快捷了,没必要用Stream API。
但是如果是自定义对象的List,使用Stream API的优势就很明显了。


首先我们定义一个测试的Book类。
public class Book {
    private String name;
    private Double price;

    public Book(String name, Double price) {
        this.name = name;
        this.price = price;
    }

    public String getName() {
        return name;
    }

    public Double getPrice() {
        return price;
    }

    public void setName(String name) {
        this.name = name;
    }

    public void setPrice(Double price) {
        this.price = price;
    }
}

然后我们使用Stream API,找到价格最高的一本书。
@Test
public void testFindOutMaxPriceBook(){
    // given
    List<Book> bookList = new ArrayList<>();
    bookList.add(new Book("平凡的世界", 22.8));
    bookList.add(new Book("Java8实战", 56.0));
    bookList.add(new Book("老人与海", 15.9));
    bookList.add(new Book("Kubernetes权威指南", 56.0));

    // then
    Book maxPriceBook = bookList.stream()
            .max(Comparator.comparing(Book::getPrice))
            .get();

    // assert
    Assert.assertEquals("Java8实战", maxPriceBook.getName());
}

尤其主要关注的是我们在max()方法中,我们传递了一个lambda函数作为比较器,用它来作为排序的逻辑以此来得到最大值。


总结

以上介绍了3中常用的从数组和List中找最大值最小值的方法

  1. for循环:代码冗余,自己重复实现比较逻辑。不推荐。
  2. 使用Collections:推荐对于保存数值的数组或List使用。
  3. 使用Stream API:推荐对于保存自定义对象的List使用。

你可能感兴趣的:(java,开发语言)