Home > Back-end >  How to use stream to get some fields from a list
How to use stream to get some fields from a list

Time:12-18

I have a list of Cars. In this List have a class Car, that have fields like make, model, color, owner, plate.

And I want to get a list of Cars that have a similar make. So I want to use stream to do this. I know how to get all car makes but not a specific kind of car make. So if I want all the car makes I would do like

Cars().stream().map(Car::getMake).collect(Collectors.toList());

But if I want just the car maker that are equal to Mazda for example, how would I do?

CodePudding user response:

If you use .map(Car::getMake) you are only returning the value of getMake to the list. If you need access to the whole car object you have to use the filter function on the stream.

Cars().stream().filter(car -> car.getMake().equals("Mazda")).collect(Collectors.toList());

Edit:

Updated code based on the comments:

Cars().stream()
      .filter(car -> car.getMake().equals("Mazda"))
      .map(Car::getPlate)
      .collect(Collectors.toList());

CodePudding user response:

Using a stream to get a specific car make will work. But have you considered using a stream to populate a map to get any list of car makes in relatively constant time?

record Car(String getMake, String getModel /* other attributes as required*/) {
     public String toString() {
         return "Make = %s, Model = %s".formatted(getMake(), getModel());
     }
 }
 List<Car> cars = List.of(
         new Car("Toyota", "Camry"),
         new Car("Toyota", "Corolla"),
         new Car("Mazda", "CX-9"),
         new Car("Mazda", "Mazda3"),
         new Car("Mazda", "CX-5"),
         new Car("Mazda", "CX-30"),
         new Car("Mazda", "MX-30"));

The following groups the cars by make and puts them in a list for that make.

Map<String, List<Car>> carMakes = 
   cars.stream().collect(Collectors.groupingBy(Car::getMake));
 
List<Car> mazda = carMakes.get("Mazda");
System.out.println("All Mazdas");
mazda.forEach(System.out::println);

List<Car> toyotas = carMakes.get("Toyota");
System.out.println("All Toyotas");
toyotas.forEach(System.out::println);

prints

All Mazdas
Make = Mazda, Model = CX-9
Make = Mazda, Model = Mazda3
Make = Mazda, Model = CX-5
Make = Mazda, Model = CX-30
Make = Mazda, Model = MX-30
All Toyotas
Make = Toyota, Model = Camry
Make = Toyota, Model = Corolla
  •  Tags:  
  • java
  • Related