使用Java流将对象列表拆分为多个字段值列表
假设我有这样的目标:使用Java流将对象列表拆分为多个字段值列表,java,java-8,java-stream,Java,Java 8,Java Stream,假设我有这样的目标: public class Customer { private Integer id; private String country; private Integer customerId; private String name; private String surname; private Date dateOfBirth; } 我有一个列表。我想用Java流拆分这样的列表,这样我就可以得到IDlist、国家list
public class Customer {
private Integer id;
private String country;
private Integer customerId;
private String name;
private String surname;
private Date dateOfBirth;
}
我有一个列表
。我想用Java流拆分这样的列表,这样我就可以得到IDlist
、国家list
、客户IDlist
等的列表
我知道我可以做得很简单,只需制作6条流,例如:
List<Integer> idsList = customerList.stream()
.map(Customer::getId)
.collect(Collectors.toList());
List idsList=customerList.stream()
.map(客户::getId)
.collect(Collectors.toList());
但我有很多次这样做似乎很无聊。我在考虑定制收集器,但我想不出任何既简洁又高效的有用方法。您可以创建如下方法:
public <T> List<T> getByFieldName(List<Customer> customerList, Function<Customer, T> field){
return customerList.stream()
.map(field)
.collect(Collectors.toList());
}
public List getByFieldName(List customerList,Function字段){
return customerList.stream()
.地图(现场)
.collect(Collectors.toList());
}
然后只需使用所需字段调用方法:
List<Integer> ids = getByFieldName(customerList, Customer::getId);
List<String> countries = getByFieldName(customerList, Customer::getCountry);
List<Integer> customerIds = getByFieldName(customerList, Customer::getCustomerId);
//...
List-id=getByFieldName(customerList,Customer::getId);
列表国家=getByFieldName(customerList,Customer::getCountry);
List CustomerId=getByFieldName(customerList,Customer::getCustomerId);
//...
对于类型安全解决方案,您需要定义一个包含所需结果的类。此类型还可以提供添加另一客户
或部分结果的必要方法:
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);
}
}
初始化3个列表并使用customerList.foreach并将每个成员添加到相关列表中怎么样可能简单的
foreach
添加到各自的列表中会是更好的选择
CustomerProperties all = customers.stream()
.collect(CustomerProperties::new, CustomerProperties::add, CustomerProperties::add);