Get the first item that matches the criteria

How to get the first item that matches the criteria in the stream? I tried this but it does not work.

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

These criteria do not work, the filter method is called in a different class than 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; } } 
+94
java java-8 java-stream
Apr 08 '14 at
source share
3 answers

This may be what you are looking for:

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



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() .get(); System.out.printf("At the first stop at Station1 there were %d passengers in the train.", firstStopAtStation1.passengerCount); } 

Exit:

 At the first stop at Station1 there were 250 passengers in the train. 
+176
Apr 08 '14 at 14:45
source share
— -

When you write a lambda expression, the argument list to the left of -> can be either a list of arguments in parentheses (possibly empty), or a single identifier without parentheses. But in the second form, the identifier cannot be declared with the type name. In this way:

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

- incorrect syntax; but

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

is correct. Or:

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

also correct if the compiler has enough information to determine the types.

+5
Apr 08 '14 at 15:02
source share

I think this is the best way:

 this.stops.stream().filter(s -> Objects.equals(s.getStation().getName(), this.name)).findFirst().orElse(null); 
+1
Aug 28 '19 at 9:27
source share



All Articles