0

How can I convert the following for loop to use a Java lambda with streams?

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;
    }
  }
}
AlBlue
  • 23,254
  • 14
  • 71
  • 91

3 Answers3

1

You can use the comparator to compare the two values

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

Also the way you compare strings is wrong

if (fruit.getType () == “Apple”)

What you proberly want

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

For more Information on that, take a look at this question: How do I compare strings in Java?

Stoffl
  • 525
  • 2
  • 4
  • 12
1

Danger, Will Robinson! Don't use == to compare strings! Use equals().

That said, this code is equivalent to your loop:

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

Note the use of a method reference (rather than a lambda) as the parameter passed to comparing().

Bohemian
  • 412,405
  • 93
  • 575
  • 722
0

This looks like it works:

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: Your sample code is terrible - please post a working sample in real syntactically correct java.

OldCurmudgeon
  • 64,482
  • 16
  • 119
  • 213