我有以下自定义列表对象 List<Person> personList
class Person(){
String name;
String age;
String countryName;
String stateName;
// getter and setter for all property
}
如果我想映射personList
基于 countryName 或 StateName 然后我会做:
List<String> countryName = personList.stream().map(Person :: getCountryName)
或
List<String> stateName = personList.stream().map(Person :: getStateName)
但现在我想在新的自定义列表对象中基于 CountryName 和 StateName 映射 personList List<Country> countryandStateList
class Country(){
String countryName;
String stateName;
// getter and setter for CountryName and StateName
}
我该怎么做?
最佳答案
首先,您用错了术语。您不是在过滤流元素,而是将流元素映射到不同类型的元素。
只需映射
到国家/地区
实例:
List<Country> countries =
personList.stream()
.map(p->new Country(p.getCountry(),p.getState()))
.collect(Collectors.toList());
这是假设相关的构造函数存在。如果不是这种情况,您还可以使用无参数构造函数,然后在创建的实例上调用 setter。
关于java - 在 Java 8 中映射自定义 List 对象的 1 个以上属性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49873033/