Sneha
Sneha

Reputation: 317

Java 8: extract a substream from a stream

I have a stream of Objects, from which I need to extract a Stream which has only some of the object attributes.

For example, from a Stream<Car>, I need to extract a Stream<CarDetails>.

Car {
   String name;
   String model;
   Engine e;
   CarType t;
   ...
}

I want to extract a Stream of objects having type CarDetails:

CarDetails {
   String name;
   String model;
}

Upvotes: 3

Views: 6286

Answers (1)

Eran
Eran

Reputation: 393986

You can achieve this with map, assuming you have the required CarDetails constructor :

Stream<Car> cars = ...
Stream<CarDetails> details = cars.map(c -> new CarDetails(c.getName(),c.getModel()));

Upvotes: 7

Related Questions