如何在流中获取符合条件的第一个元素?我尝试了这个方法,但不起作用。
this.stops.stream().filter(Stop s-> s.getStation().getName().equals(name));
那个条件不起作用,过滤方法被调用在一个名为Stop的其他类中。
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;
}
}
.findFirst().orElse(yourBackUpGoesHere);
。这也可以为 _null_。.findFirst().orElse(null);
- ifloopfindFirst()
返回一个Optional对象,可能为空。在这种情况下,调用get()
会抛出NPE异常。为了防止这种情况发生,应该使用orElse()
而不是get()
,并提供一个备选对象(例如orElse(new Station("dummy", -1))
),或者将findFirst()
的结果存储在一个变量中,并在调用get()
之前检查它是否为空,可以使用isEmpty()
进行检查。 - ifloop