0

I have a list which contains many token requestors but ID is unique and filter will returns just one object.

for (TokenRequestor requestor : tokenRequestorList) {
    if (requestor.getId().equals(tokenRequestor.getId())) {
        System.out.println("This object is unique!");
    }
}

I try write this code in Java 8:

tokenRequestorList.stream().filter(tr -> tr.getId()
        .equals(tokenRequestor.getId())).collect(Collectors.toList());

How I can filter to return a TokenRequestor? This list will be contain 1 element.

E.g:

TokenRequestor myObject = tokenRequestorList.stream()
        .filter(tr -> tr.getId().equals(tokenRequestor.getId()))....;
4
  • 2
    findFirst !? Commented May 29, 2017 at 18:58
  • What if there isn't even one? Commented May 29, 2017 at 18:59
  • I'd use findFirst(...) instead of filter(...). Commented May 29, 2017 at 18:59
  • Possible duplicate of Java 8 find first element by predicate Commented May 30, 2017 at 8:01

1 Answer 1

3
tokenRequestorList.stream()
    .filter(tr -> tr.getId().equals(tokenRequestor.getId()))
    .findAny()
    .orElse(null);

This will return any TokenRequestor instance matching the filter (in your case it will be unique), or null is nothing matches the filter.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.