Skip to content

Fetch first element of stream matching the criteria

How to get first element that matches a criteria in a stream? I’ve tried this but doesn’t work s-> s.getStation().getName().equals(name));

That criteria is not working, the filter method is invoked in an other class than Stop.

public class Train {

private final String name;
private final SortedSet<Stop> stops;

public Train(String name) { = name;
    this.stops = new TreeSet<Stop>();

public void addStop(Stop 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) { = name;
    this.stops = new ArrayList<Stop>();


public String getName() {
    return name;



This might be what you are looking for:

    .filter(/* your criteria */)

And better, if there’s a possibility of matching no element, in which case get() will throw a NPE. So use:

    .filter(/* your criteria */)
    .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 =
            .filter(e -> e.stationName.equals("Station1"))

    System.out.printf("At the first stop at Station1 there were %d passengers in the train.", firstStopAtStation1.passengerCount);

Output is:

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