Search code examples
javalambdajava-8predicatefunctional-interface

Understanding lambdas and/or predicates


I'm completely new to Java 8 and I'm trying to wrap my head around why the last test is false.

@Test
public void predicateTest() {
    Predicate<Boolean> test1 = p -> 1 == 1;
    Predicate<Boolean> test2 = p -> p == (1==1);

    System.out.println("test1 - true: "+test1.test(true));
    System.out.println("test1 - false: "+test1.test(false));
    System.out.println("test2 - true: "+test2.test(true));
    System.out.println("test2 - false: "+test2.test(false));
}

Output:

test1 - true: true

test1 - false: true

test2 - true: true

test2 - false: false


Solution

  • Elaboration

    Your first Predicate i.e.

    Predicate<Boolean> test1 = p -> 1 == 1;
    

    can be represented as

    Predicate<Boolean> test1 = new Predicate<Boolean>() {
        @Override
        public boolean test(Boolean p) {
            return true; // since 1==1 would ways be 'true'
        }
    };
    

    So irrespective of what value you pass to the above test method, it would always return true only.

    On the other hand, the second Predicate i.e.

    Predicate<Boolean> test2 = p -> p == (1==1);
    

    can be represented as

    Predicate<Boolean> test2 = new Predicate<Boolean>() {
        @Override
        public boolean test(Boolean p) {
            return p; // since 'p == true' would effectively be 'p'
        }
    };
    

    So whatever boolean value you would pass to the above test method, it would be returned as is.


    And then you can correlate how the method test corresponding to each instance test1 and test2 of the anonymous classes are invoked and what shall be the probable output.