반응형
기준과 일치하는 첫 번째 요소를 가져옵니다.
스트림의 기준과 일치하는 첫 번째 요소를 얻는 방법은 무엇입니까? 나는 이것을 시도했지만 작동하지 않습니다
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);
참고 URL : https://stackoverflow.com/questions/22940416/fetch-first-element-which-matches-criteria
반응형
'IT story' 카테고리의 다른 글
IntelliJ : Eclipse에서와 같이 변수를 자동 강조 표시하는 방법 (0) | 2020.08.26 |
---|---|
"Await yield return DoSomethingAsync ()"가 가능합니까? (0) | 2020.08.26 |
django 1.3+ 용 파일에 대한 간단한 로그 예제 (0) | 2020.08.26 |
.NET 4.7을 선택할 수 없습니다. (0) | 2020.08.26 |
하이픈이있는 자바 스크립트 객체 속성을 어떻게 참조합니까? (0) | 2020.08.26 |