📜  Java中的 IntStream min() 示例

📅  最后修改于: 2022-05-13 01:55:46.255000             🧑  作者: Mango

Java中的 IntStream min() 示例

Java 8 中的Java .util.stream.IntStream 处理原始整数。它有助于以一种新的方式解决数组中的最大值,数组中的最小值,数组中所有元素的总和以及数组中所有值的平均值等旧问题。 IntStream min()返回一个描述此流的最小元素的 OptionalInt,如果此流为空,则返回一个空的可选项。

句法 :

OptionalInt() min()

Where, OptionalInt is a container object which 
may or may not contain a int value.

下面给出了一些示例,以更好地理解该函数。
示例 1:

// Java code for IntStream min()
import java.util.*;
import java.util.stream.IntStream;
  
class GFG {
  
    // Driver code
    public static void main(String[] args)
    {
  
        // creating a stream
        IntStream stream = IntStream.of(-9, -18, 54, 8, 7, 14, 3);
  
        // OptionalInt is a container object
        // which may or may not contain a
        // int value.
        OptionalInt obj = stream.min();
  
        // If a value is present, isPresent() will
        // return true and getAsInt() will
        // return the value
        if (obj.isPresent()) {
            System.out.println(obj.getAsInt());
        }
        else {
            System.out.println("-1");
        }
    }
}

输出 :

-18

示例 2:

// Java code for IntStream min()
// to get the minimum value in range
// excluding the last element
import java.util.*;
import java.util.stream.IntStream;
  
class GFG {
  
    // Driver code
    public static void main(String[] args)
    {
  
        // To find minimum in given range
        IntStream stream = IntStream.range(50, 75);
  
        // storing the minimum value in variable
        // if it is present, else show -1.
        int minimum = stream.min().orElse(-1);
  
        // displaying the minimum value
        System.out.println(minimum);
    }
}

输出 :

50

示例 3:

// Java code for IntStream min()
// to get the minimum value in range
// excluding the last element
import java.util.*;
import java.util.stream.IntStream;
  
class GFG {
  
    // Driver code
    public static void main(String[] args)
    {
  
        // To find minimum in given range
        IntStream stream = IntStream.range(50, 50);
  
        // storing the minimum value in variable
        // if it is present, else show -1.
        int minimum = stream.min().orElse(-1);
  
        // displaying the minimum value
        System.out.println(minimum);
    }
}

输出 :

-1