Fetch first element which matches criteria

后端 未结 3 1444
执念已碎
执念已碎 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:21

    I think this is the best way:

    this.stops.stream().filter(s -> Objects.equals(s.getStation().getName(), this.name)).findFirst().orElse(null);
    
    0 讨论(0)
  • 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.

    0 讨论(0)
  • 2020-12-01 05:27

    This might be what you are looking for:

    yourStream
        .filter(/* your criteria */)
        .findFirst()
        .get();
    

    And better, if there's a possibility of matching no element, in which case get() will throw a NPE. So use:

    yourStream
        .filter(/* your criteria */)
        .findFirst()
        .orElse(null); /* You could also create a default object here */
    


    An example:
    public static void main(String[] args) {
        class Stop {
            private final String stationName;
            private final int    passengerCount;
    
            Stop(final String stationName, final int passengerCount) {
                this.stationName    = stationName;
                this.passengerCount = passengerCount;
            }
        }
    
        List<Stop> stops = new LinkedList<>();
    
        stops.add(new Stop("Station1", 250));
        stops.add(new Stop("Station2", 275));
        stops.add(new Stop("Station3", 390));
        stops.add(new Stop("Station2", 210));
        stops.add(new Stop("Station1", 190));
    
        Stop firstStopAtStation1 = stops.stream()
                .filter(e -> e.stationName.equals("Station1"))
                .findFirst()
                .orElse(null);
    
        System.out.printf("At the first stop at Station1 there were %d passengers in the train.", firstStopAtStation1.passengerCount);
    }
    

    Output is:

    At the first stop at Station1 there were 250 passengers in the train.
    
    0 讨论(0)
提交回复
热议问题