在Java 8中如何映射自定义列表对象的多个属性?

3
我有一个自定义列表对象List<Person> personList
class Person(){
    String name;
    String age;
    String countryName;
    String stateName;
// getter and setter for all property
}

如果我想根据国家名称或州名称对 personList 进行映射,那么我会这样做:

List<String> countryName = personList.stream().map(Person :: getCountryName)

或者

List<String> stateName = personList.stream().map(Person :: getStateName)

但现在我想把personList基于CountryName和StateName映射到新的自定义列表对象List<Country> countryandStateList

class Country(){
    String countryName;
    String stateName;
// getter and setter for CountryName and StateName
}

我该如何做到这一点?

3个回答

6

首先,您使用了错误的术语。您不是在过滤流元素,而是将流元素映射到不同类型的元素。

只需将流元素映射到Country实例即可:

List<Country> countries =
    personList.stream()
              .map(p->new Country(p.getCountry(),p.getState()))
              .collect(Collectors.toList());

这是在假设相关构造函数已存在的情况下。如果不是这种情况,您也可以使用无参构造函数,然后调用已创建实例上的设置器。

2
如果有多个人来自重复的国家-州集合,那么这样做不会导致重复的国家吗? - tucuxi
@tucuxi 是的,它会。楼主没有提到避免这种重复的要求。不过这很容易实现。 - Eran
感谢 @Eran 快速回答。对我有用,我会删除重复的内容。 - Nitin

0
你可以使用以下内容:
List<Country> countries = personList.stream()
            .map(person -> new Country(person.getCountryName(), 
                    person.getStateName()))
            .collect(Collectors.toList());

或者

List<Country> countries = personList.stream()
            .collect(Collectors.mapping(person -> new 
                             Country(person.getCountryName(),
                    person.getStateName()), Collectors.toList()));

两者有什么区别? - Nitin
第一个示例使用了中间的map操作,它是惰性的,并返回一个国家流,然后在collect操作中将其收集到一个列表中。 第二个示例直接使用终端的collect操作,它开始转换过程,将每个元素映射为国家,然后将其传递给另一个下游收集器以返回一个列表。 - Sajit Gupta

0
首先按照你之前的方式进行过滤,然后在你的映射函数内创建一个对象:
List countryList = personList.stream().map(person -> new Country(person.getCountryName(), person.getStateName())).collect(Collectors.toList());

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接