2

How can I convert this code to Java 8 stream?

String getFirst(String key) {
    for (Param p : params) {
        if (key.equals(p.getKey())) {
            if (!p.getValues().isEmpty()) {
                return p.getValues().get(0);
            }
        }
    }
    return "";
}
1
  • 2
    Some IDEs will do this conversion for you. I suggest you see if the IDE will do this for you. Commented Apr 5, 2015 at 1:05

1 Answer 1

8
return params.stream()
  .filter(p -> key.equals(p.getKey())
  .filter(p -> ! p.getValues().isEmpty())
  .map(p -> p.getValues().get(0))
  .findFirst()
  .orElse("");

If p.getValues() is a List, you could shorten it as:

return params.stream()
  .filter(p -> key.equals(p.getKey())
  .flatMap(p -> p.getValues().stream())
  .findFirst()
  .orElse("");

If it's not important to get the first matching value and you are ok with just getting any match, replace findFirst() with findAny(). It will more clearly mark your intent and, if somebody makes the stream parallel later on, findAny() may perform better.

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

1 Comment

Two filters could be merged into single predicate for efficiency.

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.