-1

I would like to write the code below using Stream, instead of with a for loop

private Car getCar(String CarRef, List<Car> cars) {
    for (Car car : cars) {
        if (carRef.equals(car.getName())) {
            return car;
        }
    }
    return null;
}
Johannes Kuhn
  • 14,778
  • 4
  • 49
  • 73
  • 2
    See the Javadoc of [`Stream`](https://docs.oracle.com/en/java/javase/14/docs/api/java.base/java/util/stream/Stream.html)—you have a filter operation and a "find first" operation. Would probably also be a good idea to read the [package Javadoc](https://docs.oracle.com/en/java/javase/14/docs/api/java.base/java/util/stream/package-summary.html) of `java.util.stream`. – Slaw May 13 '20 at 20:30

2 Answers2

1

Your solution should be:

cars.stream()
    .filter(c -> carRef.equals(c.getName()))
    .findFirst();
  • take the steam from a collection.
  • filter with condition which you need (you could create boolean method and use it for filtering).
  • get the first value which matches with this condition.

If you want all cars which matches to the condition, use:

.collect(Collectors.toList());

Instead of findFirst().

Mostly much better idea will be return Optional<Car> from the method than unwrap it there.

catch23
  • 17,519
  • 42
  • 144
  • 217
0

findFirst() return an optional, so the exact solution is:

return cars.stream() 
         .filter(car -> carRef.equals(car.getName())) // keep only matching elements
         .findFirst() // when 1st element matches, it triggers return
         .orElse(null);   // If not element, return null
Benjamin Caure
  • 2,090
  • 20
  • 27
  • Thank you. This format is supported on Java 9+ though, and Im working on Java 8 codebase. I think that in my case I need to type it like this in the end: return cars.stream() .filter(car -> carRef.equals(car.getName())) // keep only matching elements .findFirst() // when 1st element matches, it triggers return .orElse(null); // If not element, return null –  May 13 '20 at 20:32
  • indeed, I fixed the answer – Benjamin Caure May 13 '20 at 20:34