使用Java流将对象列表拆分为多个字段值列表 [英] Split list of objects into multiple lists of fields values using Java streams

查看:155
本文介绍了使用Java流将对象列表拆分为多个字段值列表的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

假设我有这样的对象:

public class Customer {

    private Integer id;
    private String country;
    private Integer customerId;
    private String name;
    private String surname;
    private Date dateOfBirth;
}

,我有一个List<Customer>.我想用Java流拆分这样的列表,以便获得IDs List<Integer>,国家/地区List<String>,customerIds List<Integer>等的列表.

and I have a List<Customer>. I would like to split such list with Java streams so that I would get a list of ids List<Integer>, countries List<String>, customerIds List<Integer> etc.

我知道我可以像制作6个流一样简单:

I know that I could do it as simple as making 6 streams such as:

List<Integer> idsList = customerList.stream()
        .map(Customer::getId)
        .collect(Collectors.toList());

但是这样做很多次我都觉得很乏味.我当时在考虑自定义收集器,但是我想不出任何既实用又有效的有用的东西.

but doing it that many times that I have fields seems pretty dull. I was thinking about custom Collector but I could not come up with anything useful that would be both neat and efficient.

推荐答案

对于类型安全的解决方案,您需要定义一个包含所需结果的类.此类型还可能提供添加其他Customer或部分结果的必要方法:

For a type safe solution, you’d need to define a class holding the desired results. This type may also provide the necessary methods for adding another Customer or partial result:

public class CustomerProperties {
    private List<Integer> id = new ArrayList<>();
    private List<String> country = new ArrayList<>();
    private List<Integer> customerId = new ArrayList<>();
    private List<String> name = new ArrayList<>();
    private List<String> surname = new ArrayList<>();
    private List<Date> dateOfBirth = new ArrayList<>();

    public void add(Customer c) {
        id.add(c.getId());
        country.add(c.getCountry());
        customerId.add(c.getCustomerId());
        name.add(c.getName());
        surname.add(c.getSurname());
        dateOfBirth.add(c.getDateOfBirth());
    }
    public void add(CustomerProperties c) {
        id.addAll(c.id);
        country.addAll(c.country);
        customerId.addAll(c.customerId);
        name.addAll(c.name);
        surname.addAll(c.surname);
        dateOfBirth.addAll(c.dateOfBirth);
    }
}

然后,您可以收集所有结果,例如

Then, you can collect all results like

CustomerProperties all = customers.stream()
    .collect(CustomerProperties::new, CustomerProperties::add, CustomerProperties::add);

这篇关于使用Java流将对象列表拆分为多个字段值列表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆