这可能是您正在寻找的:
yourStream
.filter(/* your criteria */)
.findFirst()
.get();
一个例子:
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 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);
}
输出是:
At the first stop at Station1 there were 250 passengers in the train.
本文通过具体示例展示了如何使用 Java 的 Stream API 来筛选并获取列表中首个符合条件的元素。示例中创建了一个 Stop 类来模拟火车站台,并在 List 中存储了多个站台实例。运用 Stream API 的 filter 方法筛选特定站台,最后使用 findFirst 和 get 方法找到并返回第一个匹配项。

被折叠的 条评论
为什么被折叠?



