web-dev-qa-db-fra.com

Récupère le premier élément qui correspond aux critères

Comment obtenir le premier élément qui correspond à un critère dans un flux? J'ai essayé mais ça ne marche pas

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

Ce critère ne fonctionne pas, la méthode de filtrage est appelée dans une autre classe que 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;
}

}
90
user2147674

C'est peut-être ce que vous recherchez:

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



Un exemple:

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

La sortie est:

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

Lorsque vous écrivez une expression lambda, la liste d'arguments située à gauche de -> peut être une liste d'arguments entre parenthèses (éventuellement vide) ou un simple identifiant sans parenthèses. Mais dans la seconde forme, l'identifiant ne peut pas être déclaré avec un nom de type. Ainsi:

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

est une syntaxe incorrecte; mais

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

est correct. Ou:

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

est également correct si le compilateur dispose de suffisamment d'informations pour déterminer les types.

5
ajb

Je pense que c'est la meilleure façon:

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