當前位置: 首頁>>代碼示例 >>用法及示例精選 >>正文


Java LongStream max()用法及代碼示例


Java 8中的java.util.stream.LongStream處理原始的long。它以新的方式幫助解決諸如在數組中找到最大值,在數組中找到最小值,數組中所有元素的總和以及數組中所有值的平均值之類的問題。 LongStream max()返回描述此流的最大元素的OptionalLong;如果此流為空,則返回一個空的Optional。

用法:

OptionalLong() max()

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

示例1:


// Java code for LongStream max() 
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.max(); 
  
        // 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"); 
        } 
    } 
}

輸出:

54

示例2:

// Java code for LongStream max() 
// to get the maximum 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 maximum in given range 
        LongStream stream = LongStream.range(50L, 75L); 
  
        // storing the maximum value in variable 
        // if it is present, else show -1. 
        long maximum = stream.max().orElse(-1); 
  
        // displaying the maximum value 
        System.out.println(maximum); 
    } 
}

輸出:

74

示例3:

// Java code for LongStream max() 
// to get the maximum 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 maximum in given range 
        LongStream stream = LongStream.range(50L, 50L); 
  
        // storing the maximum value in variable 
        // if it is present, else show -1. 
        long maximum = stream.max().orElse(-1); 
  
        // displaying the maximum value 
        System.out.println(maximum); 
    } 
}

輸出:

-1


相關用法


注:本文由純淨天空篩選整理自Sahil_Bansall大神的英文原創作品 LongStream max() in Java with examples。非經特殊聲明,原始代碼版權歸原作者所有,本譯文未經允許或授權,請勿轉載或複製。