[java] 기준과 일치하는 첫 번째 요소를 가져옵니다.

스트림의 기준과 일치하는 첫 번째 요소를 얻는 방법은 무엇입니까? 나는 이것을 시도했지만 작동하지 않습니다

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

예 :

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

출력은 다음과 같습니다.

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


답변

람다 식을 작성할 때 왼쪽에 ->있는 인수 목록은 괄호로 묶인 인수 목록 (비어있을 수 있음)이거나 괄호가없는 단일 식별자 일 수 있습니다. 그러나 두 번째 형식에서는 식별자를 형식 이름으로 선언 할 수 없습니다. 그러므로:

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

잘못된 구문입니다. 그러나

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

맞다. 또는:

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

컴파일러에 유형을 파악할 수있는 충분한 정보가있는 경우에도 정확합니다.


답변

이것이 최선의 방법이라고 생각합니다.

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


답변