Java 8 - LongPredicate interface example

Posted on December 30, 2016


java.util.function.LongPredicate is a functional interface whose functional method is  boolean test(long value). The LongPredicate interface represents an operation that takes a single argument of long type and returns a result of boolean type.

Example #1

The following example shows how to use the test () method of the LongPredicate interface with lambda expression.

LongPredicateExample1.java

package com.boraji.tutorial.lambda;

/**
 * @author imssbora
 */
import java.util.function.LongPredicate;

public class LongPredicateExample1 {
  public static void main(String[] args) {
    LongPredicate predicate = (l) -> (l > 0);
    System.out.println(predicate.test(50));
    System.out.println(predicate.test(-10));
  }
}

Output

true
false

Example #2

The following example shows how to use the default methods and(), or() and negate() of the LongPredicate interface with lambda expression.

LongPredicateExample2.java

package com.boraji.tutorial.lambda;

/**
 * @author imssbora
 */
import java.util.function.LongPredicate;

public class LongPredicateExample2 {
  public static void main(String[] args) {
    LongPredicate predicate1 = (l) -> (l > 0);
    LongPredicate predicate2 = (l) -> (l == 5);

    // Using and() method
    boolean value = predicate1.and(predicate2).test(10);
    System.out.println(value);
    
    //Using or() method 
    value=predicate1.or(predicate2).test(10);
    System.out.println(value);
    
    //Using negate() method
    value=predicate1.negate().test(10);
    System.out.println(value);
  }

}

Output

false
true
false