2017-07-31 19 views
-1

爲int的最小值陣列,我試圖做這樣的事情:與我試圖讓與流int數組的最小值流

public static int smallestInt(int[] args) { 
    return Arrays.stream((Arrays.stream(args) 
       .boxed().toArray(Integer[]::new)) 
       .mapToInt(Integer::intValue).min().getAsInt; 
} 

我的問題是什麼是最好的方式去做吧?

PS:有一個類似的問題,但沒有在這裏sterams Finding the max/min value in an array of primitives using Java

+0

它不工作?如果是這樣,什麼失敗?一般...你的問題在哪裏? –

回答

3

你是過於複雜了。

IntStream.of(args).min().getAsInt() 

注:這將拋出一個NoSuchElementException如果數組是空的,這可能是一個理想的結果。

2

我認爲你使用的流太多了。

這將只是這樣做:

int theMin = Arrays.stream(args).min().getAsInt(); 

正如方法參數ARGS已經根據方法簽名的整數數組:

public static int smallestInt(int[] args) { 
1

你可能只使用,它更容易瞭解並正確

public static int smallestInt(int[] args) { 
    return Arrays.stream(args).min().getAsInt(); 
} 
0

大多數人都提供了良好的解決方案,但他們並沒有覆蓋完全沒有最小值的情況下,應涵蓋那種情況下:

public static int smallest(int[] ints){ 
    return Arrays.stream(ints).min().orElse(Integer.MIN_VALUE); 
} 
+5

我不喜歡這種解決方案。作爲這個函數的調用者,我該如何知道數組*中最小的int是否是* Integer.MIN_VALUE,或者數組是否爲空?如果數組爲空,那麼正確的做法是拋出一個異常,'getAsInt'已經做到了。 – Michael

+1

@Michael你有一點。也許最好是直接返回IntOptional,然後調用者可以決定當沒有值時會發生什麼 – Lino

+0

是的,那會更好。 – Michael