Java Stream min()方法及实例

Java Stream min()方法及实例

Stream.min() 根据提供的比较器返回流中的最小元素。比较器是一个比较函数,它对一些对象的集合施加总的排序。min()是一个 终端操作 ,它结合流元素并返回一个汇总结果。所以,min()是缩减的一个特例。该方法返回Optional实例。

语法:

Optional< T > min(Comparator< ? super T > comparator)

其中,Optional是一个容器对象,它 可能包含也可能不包含一个非空值 和T是对象的类型 可以被这个比较器所比较的对象类型。

异常: 如果最小元素为空,该方法会抛出 NullPointerException

例子1: 整数列表中的最小值。

// Java code for Stream.min() method to get
// the minimum element of the Stream
// according to the provided Comparator.
import java.util.*;
  
class GFG {
  
    // Driver code
    public static void main(String[] args)
    {
  
        // Creating a list of integers
        List<Integer> list = Arrays.asList(-9, -18, 0, 25, 4);
  
        // Using stream.min() to get minimum
        // element according to provided Integer Comparator
        Integer var = list.stream().min(Integer::compare).get();
  
        System.out.print(var);
    }
}

输出:

-18

例2: 使用min()函数反转比较器以获得最大值。

// Java code for Stream.min() method
// to get the minimum element of the 
// Stream according to provided comparator.
import java.util.*;
  
class GFG {
  
    // Driver code
    public static void main(String[] args)
    {
  
        // Creating a list of integers
        List<Integer> list = Arrays.asList(-9, -18, 0, 25, 4);
  
        // Using Stream.min() with reverse
        // comparator to get maximum element.
        Optional<Integer> var = list.stream()
                    .min(Comparator.reverseOrder());
  
        // IF var is empty, then output will be Optional.empty
        // else value in var is printed.
        if(var.isPresent()){
        System.out.println(var.get());
        }
        else{
            System.out.println("NULL");
        }
          
    }
}

输出:

25

例3: 根据最后一个字符来比较字符串。

// Java code for Stream.min() method
// to get the minimum element of the 
// Stream according to provided comparator.
import java.util.*;
  
class GFG {
  
    // Driver code
    public static void main(String[] args)
    {
  
        // creating an array of strings
        String[] array = { "Geeks", "for", "GeeksforGeeks",
                           "GeeksQuiz" };
  
        // The Comparator compares the strings
        // based on their last characters and returns
        // the minimum value accordingly.
        Optional<String> MIN = Arrays.stream(array).min((str1, str2) -> 
                    Character.compare(str1.charAt(str1.length() - 1), 
                                      str2.charAt(str2.length() - 1)));
  
        // If a value is present,
        // isPresent() will return true
        if (MIN.isPresent()) 
            System.out.println(MIN.get()); 
        else
            System.out.println("-1"); 
    }
}

输出:

for

Python教程

Java教程

Web教程

数据库教程

图形图像教程

大数据教程

开发工具教程

计算机教程