Search code examples
javalambdajava-stream

How can I print the matching element from a stream, with a default if it doesn't exist?


I've just started working with streams and lambdas, and have figured out how to use streams-lambdas instead of a for loop.

This is the previous method I had:

public void findVehicle(){
        System.out.println("Input a vehicle rego: ");
        in = new Scanner(System.in);
        String rego = in.nextLine();

        for (int i=0; i<vehicles.size();i++){
            if (vehicles.get(i).getRego().equals(rego)){
                System.out.println(vehicles.get(i).toString());
                return;
            }
        }
        System.out.println("The vehicle does not exist.");
    }

And this is my method now:

public void findVehicle(){
        System.out.println("Input a vehicle rego: ");
        in = new Scanner(System.in);
        String rego = in.nextLine();

        vehicles.stream()
                 .filter(vehicle -> vehicle.getRego().equals(rego.toUpperCase()))
                 .forEach(System.out::println);
}

This stream works perfectly, but I want it to return once found and print the vehicle. If the vehicle is not found, I want it to print the error statement.


Solution

  • Try this.

    vehicles.stream()
        .filter(v -> v.getRego().equals(rego.toUpperCase()))
        .findFirst()
        .ifPresentOrElse(
            System.out::println,
            () -> System.out.println("The vehicle does not exist."));