📜  Java中的 LongStream min() 示例

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

Java中的 LongStream min() 示例

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

句法 :

OptionalLong() min()

Where, OptionalLong is a container object which 
may or may not contain a long value.

示例 1:

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

输出 :

-18

示例 2:

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

输出 :

50

示例 3:

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

输出 :

-1