我有下面的自定义列表对象List<Person> personList
class Person(){
String name;
String age;
String countryName;
String stateName;
// getter and setter for all property
}
Run Code Online (Sandbox Code Playgroud)
如果我想personList根据countryName或StateName进行映射,那么我会这样做:
List<String> countryName = personList.stream().map(Person :: getCountryName)
Run Code Online (Sandbox Code Playgroud)
或者
List<String> stateName = personList.stream().map(Person :: getStateName)
Run Code Online (Sandbox Code Playgroud)
但现在我想在新的自定义列表对象中根据 CountryName 和 StateName 映射 personListList<Country> countryandStateList
class Country(){
String countryName;
String stateName;
// getter and setter for CountryName and StateName
}
Run Code Online (Sandbox Code Playgroud)
我该怎么做?
首先,您使用了错误的术语。您不是在过滤流元素,而是将流元素映射到不同类型的元素。
仅map针对Country实例:
List<Country> countries =
personList.stream()
.map(p->new Country(p.getCountry(),p.getState()))
.collect(Collectors.toList());
Run Code Online (Sandbox Code Playgroud)
这是假设相关的构造函数存在。如果不是这种情况,您还可以使用无参数构造函数,然后在创建的实例上调用 setter。
| 归档时间: |
|
| 查看次数: |
836 次 |
| 最近记录: |