如何将以下for循环转换为将Java lambda与流一起使用?
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;
}
}
}
最佳答案
您可以使用comparator比较两个值
Comparator<Fruit> comp = (fruit1, fruit2) -> Integer.compare( fruit1.size(), fruit2.size());
Fruit largeApple = fruits.stream().max(comp).get();
而且比较字符串的方法是错误的
if (fruit.getType () == “Apple”)
你想要什么
if (fruit.getType().equals("Apple"))
有关更多信息,请看以下问题:
How do I compare strings in Java?