Arara
Arara

Reputation: 43

How to convert a plain Java for-loop to a Java 8 stream?

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 "";
}

Upvotes: 2

Views: 171

Answers (1)

Misha
Misha

Reputation: 28183

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.

Upvotes: 8

Related Questions