5

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

Naman
  • 27,789
  • 26
  • 218
  • 353
tisaksen
  • 329
  • 4
  • 10
  • 2
    Maybe the anonymous class representation can help you understand better as to what is happening there. Made an answer for the same https://stackoverflow.com/a/53667633/1746118 – Naman Dec 07 '18 at 10:30

3 Answers3

7

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.

Community
  • 1
  • 1
Naman
  • 27,789
  • 26
  • 218
  • 353
3

It's false because p is false and 1==1 is true so:

false == true evaluates to false.

In other words when you invoke this function with false as the argument:

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

it can be see as:

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

btw the above predicate will return whatever input you pass it, so essentially it's:

Predicate<Boolean> test2 = p -> p;
Ousmane D.
  • 54,915
  • 8
  • 91
  • 126
2

Predicate test1 = value -> 1 == 1;

Predicate test2 = value -> value == (1==1);

Test case : System.out.println("test2 - false: "+test2.test(false));

Output: false

Explanation:

You are calling the test2 method with "false", so your method 's execution will be like this:

                   false == (1==1)  => false == true => false

So the final answer will be false.