Java 8 cyclic inference warning

前端 未结 2 2021
小蘑菇
小蘑菇 2020-12-29 19:33

My knowledge about list operations is from scripting languages. So in Java I stopped on something strange in case of finding cookie with particular name.

Lis         


        
2条回答
  •  心在旅途
    2020-12-29 20:30

    Your current code returns a Stream, so you need an extra step to return a string:

    Optional auth = cookies.stream()
                .filter(c -> c.getName().equals("auth"))
                .map(Cookie::getValue)
                .findAny();
    

    Note that it returns an Optional because there may be no Cookie that matches "auth". If you want to use a default if "auth" is not found you can use:

    String auth = cookies.stream()
                .filter(c -> c.getName().equals("auth"))
                .map(Cookie::getValue)
                .findAny().orElse("");
    

提交回复
热议问题