-3

I have started to learn Java lambda and I do not understand it. I found an example.

 String[] atp = {"Rafael Nadal", "Novak Djokovic", "Stanislas Wawrinka", "David Ferrer", "Roger Federer", "Andy Murray", "Tomas Berdych", "Juan Martin Del Potro"};

players.forEach((player) -> System.out.print(player + "; "));

And it works fine, but my code does not work.

public class Counter {

    String[] atp = {"Rafael Nadal", "Novak Djokovic", "Stanislas Wawrinka", "David Ferrer", "Roger Federer", "Andy Murray", "Tomas Berdych", "Juan Martin Del Potro"};
    List<String> players =  Arrays.asList(atp);
    private int a = 7;
    private int b = 7;

    public int summ(int a, int b) {
        return a + b;
    }

    public void print(){
        players.forEach((player) -> System.out.print(player + "; "));
        summ((a,b)-> System.out.print(a + b));
    }
}

I want understand how lambda works.

This is not working - summ((a,b)-> System.out.print(a + b));

Arun Xavier
  • 763
  • 8
  • 47
user5620472
  • 2,722
  • 8
  • 44
  • 97

1 Answers1

1

You can use lambdas with functional interfaces.

What is a functional interface?

It is basically an interface that has one and only abstract method (but can have other default methods for example)

The most frequent example is the Predicate interface.

public interface Predicate <T> {
    boolean test(T t);
    // Other methods
}

This one take any Object (generics) and returns a boolean primitive.

So let's say we want to test a condition using this interface to find pair numbers in a loop, we code the following.

Predicate<Integer> function = a -> a%2 == 0;

for (int i = 0 ; i < 10 ; i++){
    if (function.test(i)){         // The primitive is AutoBoxed into an Integer Object here
        System.out.println(i);
    }
}
Yassin Hajaj
  • 21,337
  • 9
  • 51
  • 89