Fetch first element which matches criteria
如何获得与流中的条件匹配的第一个元素? 我试过这个但是没用
1 | this.stops.stream().filter(Stop s-> s.getStation().getName().equals(name)); |
该条件不起作用,filter方法在Stop之外的其他类中调用。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 | public class Train { private final String name; private final SortedSet<Stop> stops; public Train(String name) { this.name = name; this.stops = new TreeSet<Stop>(); } public void addStop(Stop stop) { this.stops.add(stop); } public Stop getFirstStation() { return this.getStops().first(); } public Stop getLastStation() { return this.getStops().last(); } public SortedSet<Stop> getStops() { return stops; } public SortedSet<Stop> getStopsAfter(String name) { // return this.stops.subSet(, toElement); return null; } } import java.util.ArrayList; import java.util.List; public class Station { private final String name; private final List<Stop> stops; public Station(String name) { this.name = name; this.stops = new ArrayList<Stop>(); } public String getName() { return name; } } |
这可能是您正在寻找的:
1 2 3 4 | yourStream .filter(/* your criteria */) .findFirst() .get(); |
一个例子:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 | 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() .get(); System.out.printf("At the first stop at Station1 there were %d passengers in the train.", firstStopAtStation1.passengerCount); } |
输出是:
1 | At the first stop at Station1 there were 250 passengers in the train. |
当您编写lambda表达式时,
1 | this.stops.stream().filter(Stop s-> s.getStation().getName().equals(name)); |
是不正确的语法; 但
1 | this.stops.stream().filter((Stop s)-> s.getStation().getName().equals(name)); |
是正确的。 要么:
1 | this.stops.stream().filter(s -> s.getStation().getName().equals(name)); |
如果编译器有足够的信息来确定类型,那么也是正确的。