2016-04-29 41 views
0

如何將以下代碼轉換爲使用帶流的Java lambda?如何用Java中的lambda和stream替換for循環?

List<Fruit> fruits = createFruitArrayList(); // creates a list of fruits 
Fruit largeApple = null; // holds the largest apple so far for 
for (Fruit fruit : fruits) { 
    if (fruit.getType() == 「Apple」) { 
    if (largeApple == null || 
    largeApple.size() < fruit.size()) { 
     largeApple = fruit; 
    } 
    } 
} 
+0

改進了格式並添加了更多描述性詞語來幫助解決問題。 – AlBlue

回答

0

這看起來像它的工作原理:

public void test() { 
    // creates a list of fruits 
    List<Fruit> fruits = Arrays.asList(
      new Fruit("Apple", 10), 
      new Fruit("Apple", 14), 
      new Fruit("Pear", 4)); 
    // Old style. 
    // holds the largest apple so far 
    Fruit largeApple = null; 
    for (Fruit fruit : fruits) { 
     if (fruit.getType().equals("Apple")) { 
      if (largeApple == null 
        || largeApple.size() < fruit.size()) { 
       largeApple = fruit; 
      } 
     } 
    } 
    System.out.println("Old: " + largeApple); 
    // New Style. 
    Optional<Fruit> max = fruits.stream() 
      .filter(f -> f.type.equals("Apple")) 
      .max(Comparator.comparing(f -> f.size)); 
    System.out.println("Lambda: " + max); 

} 

BTW:你的代碼示例是可怕的 - 請張貼在現實語法正確的Java工作示例。

+0

謝謝。示例代碼是我老師在學校給我們的示例問題 – DamiAbiola

+0

@DamiAbiola - 然後,您的老師不知道任何Java,或者您沒有正確複製它。 – OldCurmudgeon

1

您可以使用comparator兩個值

Comparator<Fruit> comp = (fruit1, fruit2) -> Integer.compare(fruit1.size(), fruit2.size()); 
Fruit largeApple = fruits.stream().max(comp).get(); 

你也比較字符串的方式比較是錯誤的

if (fruit.getType() == 「Apple」) 

你proberly要

if (fruit.getType().equals("Apple")) 

的詳細資訊在這一點上,看看這個問題: How do I compare strings in Java?

1

危險,威爾羅賓遜!不要使用==來比較字符串!使用equals()

這就是說,這個代碼就相當於你的循環:

Fruit largestApple = fruits.stream() 
    .filter(f -> f.getType().equals("Apple")) 
    .max(Comparator.comparing(Fruit::size)) 
    .orElse(null); 

注意使用方法參考(而不是拉姆達)傳遞給comparing()參數。