You can do this:
Car c1 = new Car("Toyota",1);
Car c2 = new Car("Mercedes",2);
ArrayList<Car>cars = new ArrayList<>();
ArrayList<Car>bestCars = new ArrayList<>();
cars.add(c1);
cars.add(c2);
Car c = cars.stream()
.filter(x -> x.id == 1)
.findFirst()
.get();
bestCars.add(c);
System.out.println(bestCars.get(0).name);
How this works:
cars.stream()
creates a Stream
from the ArrayList
. On this object, there is the filter
function you can use..filter(x -> x.id == 1)
will take all Car
s that have 1
as id
(there is one Car like that, in this example). x -> x.id == 1
is a lambda expression (which is a function that can be created with a simple statement like this, without having to belong to a class). The expression has one parameter x
and returns x.id == 1
, a Boolean..findFirst()
returns an Optional<Car>[^] - an Optional
is a container which may, or may not, contain a non-null object. The Optional would be empty if filter
turned out to filter out all objects and not returning a single one (but that is not the case in this example)..get()
extracts the Car
from the Optional
. Note that, if no value is present in the Optional, this will throw a NoSuchElementException
. In this example, it's clear that there is a matching value. In applications where you are not 100% certain of an Optional to have a value, use isPresent
.