Java Streams在很多年前就被引入了,但作為Java開發者,我們還沒有完全掌握這個多功能工具的威力。在這里,你將發現一些有價值的技巧,可以作為參考并應用到你的下一個項目中。
在下面的示例中,我們將使用以下類。
@Getterclass Company { private String name; private Address address; private List personList;}@Getterclass Person { private Long id; private String name;}@Getterclass Address { private String street; private City city;}@Getterclass City { private String name; private State state;}@Getterclass State{ private String name;}
以下代碼可獲取公司地址的城市名稱。
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();}
上述代碼加上空值檢查。
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();}
以下代碼獲取所有公司的人員名單列表。
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;}
可以用以下方式實現相同的功能。
public List getAllPerson(List companyList){ return companyList.stream() .map(Company::getPersonList) // 返回一個Stream> .flatMap(List::stream) // 返回一個Stream .toList(
以下代碼將返回一張地圖,其中包含每個城市的公司列表。
public Map> getCompaniesByCity(List companyList){ return companyList.stream() .collect(Collectors.groupingBy(company -> company.getAddress().getCity()));}
以下代碼會檢查是否有公司在某個城市。
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);}
使用peek方法為每個返回的城市名記錄日志。
public List getCityNames(List companyList){ return companyList.stream() .map(Company::getAddress) .map(Address::getCity) .map(City::getName) .peek(cityName -> log.info(cityName)) .toList();}
使用distinct從流中移除重復的城市名稱。
public List getUniqueCityNames(List companyList){ return companyList.stream() .map(Company::getAddress) .map(Address::getCity) .map(City::getName) .distinct() .toList();}
以上就是通過實例展示的7個技巧,希望對你有所幫助。
本文鏈接:http://www.tebozhan.com/showinfo-26-96419-0.htmlJava 流式編程的七個必學技巧
聲明:本網頁內容旨在傳播知識,若有侵權等問題請及時與本網聯系,我們將在第一時間刪除處理。郵件:2376512515@qq.com