获取匹配条件的第一个元素

use*_*674 98 java java-8 java-stream

如何获得与流中的条件匹配的第一个元素?我试过这个但是没用

this.stops.stream().filter(Stop s-> s.getStation().getName().equals(name));
Run Code Online (Sandbox Code Playgroud)

该条件不起作用,filter方法在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;
}

}
Run Code Online (Sandbox Code Playgroud)

ifl*_*oop 184

这可能是您正在寻找的:

yourStream
    .filter(/* your criteria */)
    .findFirst()
    .get();
Run Code Online (Sandbox Code Playgroud)



一个例子:

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);
}
Run Code Online (Sandbox Code Playgroud)

输出是:

At the first stop at Station1 there were 250 passengers in the train.
Run Code Online (Sandbox Code Playgroud)

  • @alexpfx 你可以使用`.findFirst().orElse(yourBackUpGoesHere);`。这也可以是 _null_ `.findFirst().orElse(null);` (4认同)
  • @iammrmehul 否。`findFirst()` 返回一个可选对象 ([JavaDoc](https://docs.oracle.com/javase/8/docs/api/java/util/stream/Stream.html#findFirst--) ),这可能是空的。在这种情况下,对 `get()` 的调用将抛出 NPE。为了防止这种情况发生,使用 `orElse()` 而不是 `get()` 并提供一个后备对象(如 `orElse(new Station("dummy", -1)`),或者存储 `findFirst( )` 并在调用 `get()` 之前用 `isEmpty()` 检查它 (3认同)
  • 事实证明我错了 - 懒惰的流阻止了效率低下:http://stackoverflow.com/questions/23696317/java-8-find-first-element-by-predicate (2认同)

Mar*_*lek 6

我认为这是最好的方法:

this.stops.stream().filter(s -> Objects.equals(s.getStation().getName(), this.name)).findFirst().orElse(null);
Run Code Online (Sandbox Code Playgroud)


ajb*_*ajb 5

当您编写lambda表达式时,其左侧的参数列表->可以是带括号的参数列表(可能为空),也可以是不带括号的单个标识符。但是在第二种形式中,不能使用类型名称声明标识符。从而:

this.stops.stream().filter(Stop s-> s.getStation().getName().equals(name));
Run Code Online (Sandbox Code Playgroud)

语法错误;但

this.stops.stream().filter((Stop s)-> s.getStation().getName().equals(name));
Run Code Online (Sandbox Code Playgroud)

是正确的。要么:

this.stops.stream().filter(s -> s.getStation().getName().equals(name));
Run Code Online (Sandbox Code Playgroud)

如果编译器具有足够的信息来找出类型,则也是正确的。