Paul Erdos
Paul Erdos

Reputation: 1375

How do you retrieve the largest element of List that matches a condition?

New to Java 8 and lambdas in general. Here's what I have:

A simple Credentials class:

public interface Credentials {

    boolean isPasswordEnabled();

    String getCreatedDate();
}

A simple service to return the list of credentials:

List<Credentials> credentials =  credentialsService.getCredentials();

I need to grab the most recently created password that is also enabled. This is what I have so far, but that only takes care of the date part. How do I integrate the isPasswordEnabled check?

Credentials latestCredentials = Collections.max(credentials, Comparator.comparing(c -> c.getCreatedDate()));

Upvotes: 1

Views: 55

Answers (2)

Bohemian
Bohemian

Reputation: 425258

Use a filter, then find max:

Credentials latestCredentials = credentials.stream()
  .filter(Credentials::isPasswordEnabled)
  .max(Comparator.comparing(Credentials::getCreatedDate))
  .get();

Note that since max() returns Optional, you need to then call .get() to get the max.

If there are no enabled elements (or credentials is empty), you'll get a NoSuchElementException. If you want to throw a particular exception for this case, instead of calling .get() call .orElseThrow(SomeException::new).

Upvotes: 1

HeyHo
HeyHo

Reputation: 49

Use this:

credentials.stream()
.filter(Credentials::isPasswordEnabled)
.max(Comparator.comparing(Credentials::getCreatedDate))

Upvotes: 1

Related Questions