Skip to main content Link Menu Expand (external link) Document Search Copy Copied

Predicate types

Header Image

Ahoy there, mateys! Today we be talkin’ about predicate types in Java Guava. Now ye may be wonderin’, “What in Davy Jones’ locker be a predicate type?” Well, fear not, we’ll be divin’ into that very topic.

Definition and usage of Guava predicate types

A predicate type is a fancy term for a function that takes in one argument and returns a boolean value. In Guava, a predicate is represented by the Predicate interface. This interface has one method: apply(T input). This method takes in a generic argument T, which can be any object, and returns a boolean value.

So why do we need predicates? Well, predicates can be very useful when filtering collections or performing conditional checks in code. For example, let’s say ye have a list of pirates and ye want to filter out any pirates who aren’t captains. Ye could use a predicate to do this filtering:

List<Pirate> pirates = // get list of pirates
Predicate<Pirate> isCaptain = pirate -> pirate.getRank() == Rank.CAPTAIN;
List<Pirate> captains = pirates.stream()
                               .filter(isCaptain)
                               .collect(Collectors.toList());

In this example, we’ve defined a predicate isCaptain that takes in a Pirate object and checks whether its rank is equal to Rank.CAPTAIN. We then use this predicate to filter out any pirates who aren’t captains and collect the resulting list of captain pirates.

Examples of using predicate types

Now that we know what predicates are, let’s dive into some examples of how we can use them in our code.

Filtering a collection

As we saw in the previous example, predicates can be very useful for filtering collections. Let’s say ye have a list of plunder items and ye want to filter out any items that have already been claimed by the crew. Ye could use a predicate to do this filtering:

List<Plunder> unclaimedItems = // get list of plunder items
Predicate<Plunder> isClaimed = plunder -> plunder.isClaimed();
List<Plunder> unclaimed = unclaimedItems.stream()
                                         .filter(isClaimed.negate())
                                         .collect(Collectors.toList());

In this example, we’ve defined a predicate isClaimed that takes in a Plunder object and checks whether it has been claimed by the crew. We then use the negate() method to get the opposite of this predicate (i.e., whether an item is not claimed) and use it to filter out any claimed items and collect the resulting list of unclaimed items.

Performing conditional checks

Predicates can also be useful for performing conditional checks in code. Let’s say ye have a function that takes in a Ship object and ye want to check whether it’s seaworthy (i.e., has a hull integrity greater than 50%). Ye could use a predicate to perform this check:

Predicate<Ship> isSeaworthy = ship -> ship.getHullIntegrity() > 50;
if (isSeaworthy.test(myShip)) {
    // do something if ship is seaworthy
} else {
    // do something else if ship is not seaworthy
}

In this example, we’ve defined a predicate isSeaworthy that takes in a Ship object and checks whether its hull integrity is greater than 50. We then use the test() method to apply this predicate to myShip and perform a conditional check to determine whether to do something or something else.

Conclusion

In conclusion, predicate types in Java Guava are a powerful toolfor filtering collections and performing conditional checks in code. They allow us to write more expressive and readable code by encapsulating boolean logic in a reusable function.

When working with predicates, it’s important to keep in mind their potential impact on performance. Predicates that perform expensive operations or have side effects can slow down our code, so we should strive to keep our predicates simple and lightweight whenever possible.

In summary, if ye be needin’ to filter collections or perform conditional checks in yer code, consider using predicate types in Java Guava. They can make yer code more expressive, readable, and reusable. So hoist the Jolly Roger, set sail on yer coding adventure, and give predicates a try!

Examples of using predicate types (continued)

Validating input

Predicates can also be used to validate input in functions. Let’s say ye have a function that takes in a String representing a pirate’s name and ye want to validate that the name is not empty or null. Ye could use a predicate to perform this validation:

Predicate<String> isValidName = name -> name != null && !name.trim().isEmpty();
public void hirePirate(String name) {
    if (isValidName.test(name)) {
        // hire the pirate
    } else {
        throw new IllegalArgumentException("Invalid name");
    }
}

In this example, we’ve defined a predicate isValidName that takes in a String and checks whether it’s not null and not empty (after trimming any whitespace). We then use the test() method to apply this predicate to the name argument in our hirePirate function and throw an exception if the name is invalid.

Chaining predicates

Predicates can also be chained together using the and(), or(), and negate() methods. Let’s say ye have a list of pirates and ye want to filter out any pirates who aren’t captains and aren’t currently on leave. Ye could use chained predicates to do this filtering:

List<Pirate> pirates = // get list of pirates
Predicate<Pirate> isCaptain = pirate -> pirate.getRank() == Rank.CAPTAIN;
Predicate<Pirate> isOnLeave = pirate -> pirate.isOnLeave();
Predicate<Pirate> isCaptainAndNotOnLeave = isCaptain.and(isOnLeave.negate());
List<Pirate> eligibleCaptains = pirates.stream()
                                        .filter(isCaptainAndNotOnLeave)
                                        .collect(Collectors.toList());

In this example, we’ve defined two predicates isCaptain and isOnLeave that check whether a pirate is a captain and whether they’re on leave, respectively. We then use the and() and negate() methods to chain these predicates together and define a new predicate isCaptainAndNotOnLeave that checks whether a pirate is a captain and not on leave. We use this predicate to filter out any ineligible pirates and collect the resulting list of eligible captains.