Java 8 cyclic inference warning

前端 未结 2 2003
小蘑菇
小蘑菇 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:26

    In essence, what this rather cryptic error message is saying is "the output of the stream sequence doesn't match what you are assigning it to in the end", ex:

    String s = list.stream().map(s -> s); // this doesn't result in a String...
    

    .findFirst().get() So to debug compilation, remove the assignment (temporarily), or, as the other answer says, add something that makes it return a String by collecting (ex: .collect(Collectors.joining(","))) or (getting like .findFirst().get()), or change the assignment, like Stream<String> stream = list.stream().map(...)

    0 讨论(0)
  • 2020-12-29 20:30

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

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

    Note that it returns an Optional<String> 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("");
    
    0 讨论(0)
提交回复
热议问题