Java 流式編程的七個必學技巧
作者:學研君
作為Java開發(fā)者,我們還沒有完全掌握Java Streams這個多功能工具的威力。在這里,你將發(fā)現(xiàn)一些有價值的技巧,可以作為參考并應用到你的下一個項目中。
Java Streams在很多年前就被引入了,但作為Java開發(fā)者,我們還沒有完全掌握這個多功能工具的威力。在這里,你將發(fā)現(xiàn)一些有價值的技巧,可以作為參考并應用到你的下一個項目中。
在下面的示例中,我們將使用以下類。
@Getter
class Company {
private String name;
private Address address;
private List personList;
}
@Getter
class Person {
private Long id;
private String name;
}
@Getter
class Address {
private String street;
private City city;
}
@Getter
class City {
private String name;
private State state;
}
@Getter
class State{
private String name;
}
1. 使用方法引用簡化地圖
以下代碼可獲取公司地址的城市名稱。
public List getCityNames(List companyList){
return companyList.stream()
.map(company -> company.getAddress().getCity().getName())
.toList();
}
可以替換為以下更具可讀性的版本。
public List getCityNames(List companyList){
return companyList.stream()
.map(Company::getAddress)
.map(Address::getCity)
.map(City::getName)
.toList();
}
2. 空值檢查
上述代碼加上空值檢查。
public List getCityNames(List companyList){
return companyList.stream()
.map(Company::getAddress)
.filter(Objects::nonNull)
.map(Address::getCity)
.filter(Objects::nonNull)
.map(City::getName)
.filter(Objects::nonNull)
.toList();
}
3. 從流的流到流
以下代碼獲取所有公司的人員名單列表。
public List getAllPerson(List companyList){
// 生成一個Person列表的列表
List> partialResult = companyList.stream()
.map(Company::getPersonList)
.toList();
// 將每個Person列表添加到結果中
List result = new ArrayList<>();
partialResult.forEach(result::addAll);
return result;
}
可以用以下方式實現(xiàn)相同的功能。
public List getAllPerson(List companyList){
return companyList.stream()
.map(Company::getPersonList) // 返回一個Stream>
.flatMap(List::stream) // 返回一個Stream
.toList(
4. 按屬性分組
以下代碼將返回一張地圖,其中包含每個城市的公司列表。
public Map> getCompaniesByCity(List companyList){
return companyList.stream()
.collect(Collectors.groupingBy(company -> company.getAddress().getCity()));
}
5. 檢查流中是否有項目
以下代碼會檢查是否有公司在某個城市。
public boolean hasCompanyInCity(List companyList, String cityName){
return companyList.stream()
.map(Company::getAddress)
.map(Address::getName)
.anyMatch(cityName::equals);
}
同樣的方法也適用于noneMatch,如果你想檢查某個城市是否有公司。
public boolean hasNoCompanyInCity(List companyList, String cityName){
return companyList.stream()
.map(Company::getAddress)
.map(Address::getName)
.noneMatch(cityName::equals);
}
6. 記錄日志
使用peek方法為每個返回的城市名記錄日志。
public List getCityNames(List companyList){
return companyList.stream()
.map(Company::getAddress)
.map(Address::getCity)
.map(City::getName)
.peek(cityName -> log.info(cityName))
.toList();
}
7. 獲取唯一的城市名稱
使用distinct從流中移除重復的城市名稱。
public List getUniqueCityNames(List companyList){
return companyList.stream()
.map(Company::getAddress)
.map(Address::getCity)
.map(City::getName)
.distinct()
.toList();
}
以上就是通過實例展示的7個技巧,希望對你有所幫助。
責任編輯:趙寧寧
來源:
Java學研大本營