12/10/2018

[Java8] Predicate Functional Interface

Definition of Predicate

  • a : something that is affirmed or denied of the subject in a proposition in logic
  • b : a term designating a property or relation

From java definition

Represents a predicate (boolean-valued function) of one argument.

Here are some test cases.
Evaluates this predicate on the given argument.

   public void testPredicateTest()
   {
      //given
      Predicate<Integer> isEven = (num) -> num % 2 == 0;
      //verify
      Assertions.assertTrue(isEven.test(4));
      Assertions.assertTrue(isEven.test(0));
   }

A composed predicate that represents a short-circuiting logical AND of this predicate and another.

   public void testPredicateTestAnd()
   {
      //given
      Predicate<Integer> isEven = (num) -> num % 2 == 0;
      Predicate<Integer> isEvenAndGreater100 = isEven.and((num) -> num > 100);
      //verify
      Assertions.assertTrue(isEvenAndGreater100.test(102));
      Assertions.assertFalse(isEvenAndGreater100.test(101));
      Assertions.assertFalse(isEvenAndGreater100.test(3));
   }

A composed predicate that represents a short-circuiting logical OR of this predicate and another.

   public void testPredicateTestOr()
   {
      //given
      Predicate<Integer> isEven = (num) -> num % 2 == 0;
      Predicate<Integer> isEvenOrGreater100 = isEven.or((num) -> num > 100);
      //verify
      Assertions.assertTrue(isEvenOrGreater100.test(102));
      Assertions.assertTrue(isEvenOrGreater100.test(101));
      Assertions.assertFalse(isEvenOrGreater100.test(3));

   }
   

A predicate that tests if two arguments are equal according to {@link Objects#equals(Object, Object)}.

   public void testPredicateIsEqual()
   {
      Assertions.assertTrue(Predicate.isEqual(20).test(20));
   }

No comments:

Post a Comment