DEV Community

Cover image for How to create a boolean arrow function in Java 🏹
Benjamin Rancourt
Benjamin Rancourt

Posted on • Originally published at benjaminrancourt.ca on

How to create a boolean arrow function in Java 🏹

Since I am more experienced with JavaScript than Java, I often search on the Web to find out how to do X in Java when working on Java projects. I guess this is common among people who are able to code in a lot of languages. 😛

Recently, I was just looking to create an arrow function , to add more readability to my Java code. In JavaScript, it's pretty simple:

const isUdeSCategory = (category) => category.displayName === "UdeS";

Enter fullscreen mode Exit fullscreen mode

But, as always, in Java, you have to know the right class to do the same... In this case, after discovering the Predicate class, I was able to quicly adapt my code as I wanted:

final Predicate<OutlookCategory> isUdeSCategory = category -> category?.displayName == "UdeS";

// To keep things simple, I used the equal comparison, but in reality, the function looks like as
// final Predicate<OutlookCategory> predicate = category -> Objects.equals(category.displayName, "UdeS");
// to be null-safe.

Enter fullscreen mode Exit fullscreen mode

If you want to know more about the Predicate interface, JournalDev has a quick article on it named Java Predicate.

I'm pretty sure there are other interfaces for other types of arrow functions in Java, but I guess I'll learn them when I need to! 😉

Top comments (0)