对象字段java_Java 8流分组以对象作为键的对象字段

你可以尝试这样的事情:

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);

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值