I figured out how to use streams-lambdas instead of for loop (just started with streams and lambdas)
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 printed the vehicle and if vehicle not found the method continues and prints the error statement. Thanks!
CodePudding user response:
Try this.
vehicles.stream()
.filter(v -> v.getRego().equals(rego.toUpperCase()))
.findFirst()
.ifPresentOrElse(
System.out::println,
() -> System.out.println("The vehicle does not exist."));