How to Create a Boolean Arrow Function in Java 🏹

Even if it's simple, it's easier in JavaScript because the language is not typed. 😆

1 min read
How to Create a Boolean Arrow Function in Java 🏹
Photo by Pixabay from Pexels

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 can 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";

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 quickly 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.

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! 😉