How to use Predicate in Java to Return Always a Boolean true value


If you have a use case where you always want to return a boolean true value for a function then you can make use of the Java 8 Predicate functional interface in the following way.


Predicate<Object> alwaysTrue = obj -> true;

No matter what you do with this function, this lambda expression will always result as a boolean true.


Example:
package org.code2care.examples;

import java.util.ArrayList;
import java.util.function.Predicate;

public class Example {

    public static void main(String[] args) {

        Predicate<Object> alwaysTrue = obj -> true;

        System.out.println(alwaysTrue.test(100));

        System.out.println(alwaysTrue.test("Code2care"));

        System.out.println(alwaysTrue.test(new ArrayList<>()));

        System.out.println(alwaysTrue.test(null));
    }
}

Output:


true
true
true
true


You can repurpose this same code to work with a case where you always want the result from the predicate to be always false.


This is not an AI-generated article but is verified & demonstrated by a human on an M1 Mac and Java JDK 21.

Please support independent contributors like Code2care by donating a coffee.

Buy me a coffee!

Buy Code2care a Coffee!
-

Facing issues? Have Questions? Post them here! I am happy to answer!


Author Info:

Rakesh (He/Him) is a seasoned developer with over 10 years of experience in web and app development, and a deep knowledge of operating systems. Author of insightful How-To articles for Code2care.

Follow him on: X

You can also reach out to him via e-mail: rakesh@code2care.org

Copyright © Code2care 2024 | Privacy Policy | About Us | Contact Us | Sitemap