如何获取流中与条件匹配的第一个元素?我试过了,但没用

this.stops.stream().filter(Stop s-> s.getStation().getName().equals(name));

如果条件不起作用,则在Stop以外的其他类中调用filter方法.

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 */


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

输出为:

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

Java相关问答推荐

在Java 11+中,我们可以在不编译多个文件的情况下以某种方式执行吗?

无法从TemporalAccessor获取Instant:{},ISO解析为2024-04- 25 T14:32:42类型为java.time. form.Parsed

为什么我的画布没有显示在PFA应用程序中?

查找最大子数组的和

如何转换Tue Feb 27 2024 16:35:30 GMT +0800 String至ZonedDateTime类型""

将成为一个比较者.比较…在现代Java中,编译器会对`CompareTo`方法进行优化吗?

Java中后期绑定的替代概念

Java List with all combinations of 8 booleans

给定Java枚举类,通过值查找枚举

Java FX中的河内之塔游戏-在游戏完全解决之前什么都不会显示

无法初始化JPA实体管理器工厂:无法确定为Java类型<;类>;推荐的JdbcType

Java编译器抛出可能未正确初始化的错误?

try 判断可选参数是否为空时出现空类型安全警告

Spring-Boot Kafka应用程序到GraalVM本机映像-找不到org.apache.kafka.streams.processor.internals.DefaultKafkaClientSupplier

内存和硬盘中的Zip不同,这会导致下载后的Zip损坏

在Eclipse中可以使用外部字体吗?

如何在JSP中从select中获取值并将其放入另一个select

设置背景时缺少Android编辑文本下划线

使用原子整数的共享计数器并发增量

原始和参数化之间的差异调用orElseGet时可选(供应商)