你可以尝试这样的事情:
Map> listing = cars.stream().collect(Collectors.groupingBy(Car::getManufacturer));
因此,这将由它的制造商对所有汽车进行分组,输出将是这样的:
TOYOTA = [AURIS的AURIS params,AVIA的AVIA params],MERCEDES = [S500的S500 params ...]
EDIT 2
public class Main {
List listOfCars = new ArrayList<>();
public static void main(String[] args) {
List listOfCars = new ArrayList<>();
listOfCars.add(new Car(new Manufacturer("Toyota"), "Toyota A"));
listOfCars.add(new Car(new Manufacturer("Toyota"), "Toyota B"));
listOfCars.add(new Car(new Manufacturer("Jeep"), "Jeep A"));
listOfCars.add(new Car(new Manufacturer("Mercedes"), "Mercedes C"));
listOfCars.add(new Car(new Manufacturer("Toyota"), "Toyota C"));
listOfCars.add(new Car(new Manufacturer("Audi"), "Audi A"));
listOfCars.add(new Car(new Manufacturer("Toyota"), "Toyota C"));
Map> listOfCarsByManufacturers = listOfCars.stream().collect(Collectors.groupingBy(d->d.getManufacturer().getName()));
System.out.println(listOfCarsByManufacturers);
}
}
public class Car {
private Manufacturer manufacturer;
private String nameOfTheCar;
public Car() {
}
public Car(Manufacturer manufacturer, String nameOfTheCar) {
this.manufacturer = manufacturer;
this.nameOfTheCar = nameOfTheCar;
}
public Manufacturer getManufacturer() {
return manufacturer;
}
public String getNameOfTheCar() {
return nameOfTheCar;
}
@Override
public String toString() {
return "Manufacturer: " + getManufacturer() + ", name: " + getNameOfTheCar();
}
}
public class Manufacturer {
private String name;
public Manufacturer() {
}
public Manufacturer(String name) {
this.name = name;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
@Override
public String toString() {
return getName();
}
}
EDIT 3:
Map> listOfCarsByManufacturers = listOfCars.stream().collect(Collectors.groupingBy(d->d.getManufacturer().getName()));
System.out.println(listOfCarsByManufacturers);