簡體   English   中英

合並與 List 中每個唯一對象相關的數據,並使用 Streams 將它們轉換為另一種類型的 List

[英]Merge the data relating to each unique Object in a List and transform them into a List of another Type using Streams

我有一個 Bean 列表( List 1 ),我想將其轉換為另一個列表( List 2 )。

我已經成功地做到了這一點。 但我覺得它太復雜了:再次挑出id的 +循環+

我的問題是:是否有可能使它更簡單?

樣本數據 - List1:

[Customer [id=1, name=jon, carType=fiat, color=black], 
 Customer [id=2, name=din, carType=ford, color=yellow], 
 Customer [id=1, name=jon, carType=benz, color=white], 
 Customer [id=1, name=jon, carType=volvo, color=red], 
 Customer [id=3, name=fin, carType=volvo, color=black], 
 Customer [id=3, name=fin, carType=fiat, color=green], 
 Customer [id=4, name=lara, carType=bmw, color=red], 
 Customer [id=5, name=tina, carType=toyota, color=white], 
 Customer [id=5, name=tina, carType=fiat, color=yelow], 
 Customer [id=6, name=bogi, carType=benz, color=black]]

樣本數據 - List2:

ImprovedCustomer [id=1, name=jon, cars=[Car [carType=fiat, color=black], Car [carType=benz, color=white], Car [carType=volvo, color=red]]]
ImprovedCustomer [id=2, name=din, cars=[Car [carType=ford, color=yellow]]]
ImprovedCustomer [id=3, name=fin, cars=[Car [carType=volvo, color=black], Car [carType=fiat, color=green]]]
ImprovedCustomer [id=4, name=lara, cars=[Car [carType=bmw, color=red]]]
ImprovedCustomer [id=5, name=tina, cars=[Car [carType=toyota, color=white], Car [carType=fiat, color=yelow]]]
ImprovedCustomer [id=6, name=bogi, cars=[Car [carType=benz, color=black]]]

我的代碼:

import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

public class App {

    public static void main(String[] args) {
        List<Customer> list = new ArrayList<>();
        list.add(new Customer(1, "jon", "fiat", "black"));
        list.add(new Customer(2, "din", "ford", "yellow"));
        list.add(new Customer(1, "jon", "benz", "white"));
        list.add(new Customer(1, "jon", "volvo", "red"));
        list.add(new Customer(3, "fin", "volvo", "black"));
        list.add(new Customer(3, "fin", "fiat", "green"));
        list.add(new Customer(4, "lara", "bmw", "red"));
        list.add(new Customer(5, "tina", "toyota", "white"));
        list.add(new Customer(5, "tina", "fiat", "yelow"));
        list.add(new Customer(6, "bogi", "benz", "black"));

        List<Integer> ids = list.stream().map(Customer::getId).distinct().collect(Collectors.toList());

        List<ImprovedCustomer> ImprovedCustomers = new ArrayList<>();

        for (int id : ids) {
            ImprovedCustomer improvedCustomer = new ImprovedCustomer(id);
            List<Car> collect = list.stream().filter(a -> a.getId().equals(id)).map(a -> {
                if (improvedCustomer.getName() == null) {
                    improvedCustomer.setName(a.getName());
                }
                return new Car(a.getCarType(), a.getColor());
            }).collect(Collectors.toList());

            improvedCustomer.setCars(collect);
            ImprovedCustomers.add(improvedCustomer);
        }
    }
}

class Customer {

    private Integer id;
    private String name;
    private String carType;
    private String color;

    public Customer(Integer id, String name, String carType, String color) {
        super();
        this.id = id;
        this.name = name;
        this.carType = carType;
        this.color = color;
    }

    public Integer getId() {
        return id;
    }

    public void setId(Integer id) {
        this.id = id;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public String getCarType() {
        return carType;
    }

    public void setCarType(String carType) {
        this.carType = carType;
    }

    public String getColor() {
        return color;
    }

    public void setColor(String color) {
        this.color = color;
    }
}

class Car {

    private String carType;
    private String color;

    public Car(String carType, String color) {
        super();
        this.carType = carType;
        this.color = color;
    }

    public String getCarType() {
        return carType;
    }

    public void setCarType(String carType) {
        this.carType = carType;
    }

    public String getColor() {
        return color;
    }

    public void setColor(String color) {
        this.color = color;
    }
}

class ImprovedCustomer {

    private Integer id;
    private String name;
    private List<Car> cars;

    public ImprovedCustomer() {
        super();
    }

    public ImprovedCustomer(Integer id) {
        super();
        this.id = id;
    }

    public ImprovedCustomer(Integer id, String name, List<Car> cars) {
        super();
        this.id = id;
        this.name = name;
        this.cars = cars;
    }

    public Integer getId() {
        return id;
    }

    public void setId(Integer id) {
        this.id = id;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public List<Car> getCars() {
        return cars;
    }

    public void setCars(List<Car> cars) {
        this.cars = cars;
    }
}

您當前的解決方案對每個唯一id客戶列表執行迭代。

正如@Johannes Kuhn在評論中指出的那樣,您可以通過使用收集器groupingBy(classifier, downstream)來消除冗余迭代。 使用這個收集器,我們可以在一次迭代中將每個具有唯一id客戶映射到汽車列表

然后根據groupingBy()生成的地圖的每個條目構造一個ImprovedCustomer對象列表。

注意:為了使用這種方法,要么Customer類應該基於idname屬性實現equals/hashCode契約,要么我們需要使用一個輔助記錄(或類)來包裝一個Customer對象。 為簡單起見,我假設我們可以依賴Customer類的equals/hashCode實現。

因此,在下面的代碼中作為分類器函數,我應用了Function.identity() (即,一個將是客戶本身)和作為下游收集器收集器mapping()toList()的組合,它將每個客戶轉換為Car對象,並將映射到同一客戶的汽車收集到一個列表中。

public static void main(String[] args) {
    List<Customer> customers = // initializing the list of customers

    List<ImprovedCustomer> improvedCustomers = customers.stream()
        .collect(Collectors.groupingBy(
            Function.identity(),
            Collectors.mapping(cust -> new Car(cust.getCarType(), cust.getColor()),
                Collectors.toList())
        ))
        .entrySet().stream()
        .map(entry -> new ImprovedCustomer(entry.getKey().getId(), entry.getKey().getName(), entry.getValue()))
        .collect(Collectors.toList());
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM