Fetch first element which matches criteria

后端 未结 3 1462
执念已碎
执念已碎 2020-12-01 05:09

How to get first element that matches a criteria in a stream? I\'ve tried this but doesn\'t work

this.stops.stream().filter(Stop s-> s.getStation().getNam         


        
3条回答
  •  悲哀的现实
    2020-12-01 05:26

    When you write a lambda expression, the argument list to the left of -> can be either a parenthesized argument list (possibly empty), or a single identifier without any parentheses. But in the second form, the identifier cannot be declared with a type name. Thus:

    this.stops.stream().filter(Stop s-> s.getStation().getName().equals(name));
    

    is incorrect syntax; but

    this.stops.stream().filter((Stop s)-> s.getStation().getName().equals(name));
    

    is correct. Or:

    this.stops.stream().filter(s -> s.getStation().getName().equals(name));
    

    is also correct if the compiler has enough information to figure out the types.

提交回复
热议问题