我有如下的类地址。
class Address {
String address;
String phone1;
String phone2;
getters & setters
}
我的要求是从地址列表中获取电话1和电话2的区别,我可以得到如下结果。但有没有更好的方法来获得结果呢?
Address add1 = new Address("NAME1", null, null);
Address add2 = new Address("NAME2", "123", null);
Address add3 = new Address("NAME3", null, "456");
List<Address> addressList = Arrays.asList(add1, add2, add3);
Set<String> distinctPhoneNo = addressList.stream()
.filter(add -> StringUtils.isNotBlank(add.getPhone1()))
.map(Address::getPhone1)
.distinct()
.collect(Collectors.toSet());
distinctPhoneNo.addAll(addressList.stream()
.filter(add -> StringUtils.isNotBlank(add.getPhone2()))
.map(Address::getPhone2)
.distinct()
.collect(Collectors.toSet()));
预期的结果是 ["123", "456"]
它可以稍微简化,将地址映射到两个电话流中(.distinct()
不需要,因为它被收集到 Set
):
Set<String> distinctPhoneNo = addressList.stream()
.flatMap(address -> Stream.of(address.getPhone1(), address.getPhone2()))
.filter(StringUtils::isNotBlank)
.collect(Collectors.toSet());
或与列表。
List<String> distinctPhoneNo = addressList.stream()
.flatMap(address -> Stream.of(address.getPhone1(), address.getPhone2()))
.filter(StringUtils::isNotBlank)
.distinct()
.collect(Collectors.toList());