Search code examples
javajava-8java-streamcollectors

Java 8: How to get particular value within object inside list without converting stream back to list and fetch value at 0th location?


I need to return value from href() inside a list of links where Rel value is String.

class Links{
    String rel;
    String href;
 }

class 2{
    List<Links> links
 }

Following code is doing so but it is not looking cool

return links.stream().filter(d -> StringUtils.equalsIgnoreCase(d.getRel(), "Self")).collect(Collectors.toList()).get(0).getHref();

Is there any way to fetch getHref directly from list in place of converting it back to list and get 0th element.


Solution

  • Yes, use findFirst():

    return links.stream()
                .filter(d -> StringUtils.equalsIgnoreCase(d.getRel(), "Self"))
                .findFirst() // returns an Optional<Links>
                .map(Links::getHref) // returns an Optional<String>
                .orElse(null); // returns String (either getHref of the found Links instance, or
                               // null if no instance passed the filter)