gpt4 book ai didi

java - 获取符合条件的流的第一个元素

转载 作者:IT老高 更新时间:2023-10-28 11:34:45 25 4
gpt4 key购买 nike

如何在流中获取符合条件的第一个元素?这个我试过了,还是不行

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;
}

}

最佳答案

这可能是您正在寻找的:

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

更好的是,如果有可能不匹配任何元素,在这种情况下 get() 将抛出 NPE。所以使用:

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


一个例子:
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);
}

输出是:

At the first stop at Station1 there were 250 passengers in the train.

关于java - 获取符合条件的流的第一个元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22940416/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com