Optional – filter() operation

The filter() method from the Java Optional class is used to filter the Optional value by matching it with the given Predicate. It is basically the same as the filter() method from Streams API, just in this case we are performing the filter on one value, contained in Optional, not on the stream of elements.

Syntax

public Optional<T> filter(Predicale<T> predicate)


Using the filter() operation from Optional class – examples

Example 1:
Get the value from the Optional, filter it, transform and print to the console.

class Test {

  public static void main(String[] args) {
    Optional<String> stringOptional = Optional.ofNullable("alegru coding");

    stringOptional.filter(str -> str.length() > 10)
            .map(String::toUpperCase)
            .ifPresent(System.out::println);
  }
}
Output: ALEGRU CODING


Example 2:
Get the user object from the Optional, and print only if the user has a premium membership type.

class Test {

  public static void main(String[] args) {
    Optional<User> userOptional = Optional.ofNullable(new User("John", "john123", "premium", "5th Avenue"));

    userOptional.filter(user -> user.getMembershipType().equals("premium"))
            .ifPresent(System.out::println);
  }
}

class User {
  private String name;
  private String username;
  private String membershipType;
  private String address;

  public User(String name, String username, String membershipType, String address) {
    this.name = name;
    this.username = username;
    this.membershipType = membershipType;
    this.address = address;
  }

  public String getMembershipType() {
    return membershipType;
  }

  @Override
  public String toString() {
    return "name: " + name + " ," + "username: " + username;
  }
}
Output: name: John ,username: john123


In case the value does not pass the filter() operation, the output will be empty.

That was all about Optional filter() operation in Java. Proceed to the next lesson.

Happy coding!

 

Leave a Reply

Your email address will not be published. Required fields are marked *