[英]Filter an ArrayList of Objects using Java Streams to return an ArrayList of type String
我在 SO 上找不到確切的解決方案。 我有一個Crowd
class ,它由一個Crowd
object 組成,它是一個People
類型的 arraylist 。 People
是一個 class 屬性String name, Double bankBalance, Integer numberOfCarsOwned
。
在我的人群中 class 我有以下方法,我試圖按以字母 P 開頭的名稱進行過濾,並返回這些String
類型的 arraylist :
public ArrayList<String> filterByLetterP(){
ArrayList<String> filteredNames = this.crowd.stream()
.filter(name -> name.getName().contains("P"));
return filteredNames;
}
我的錯誤是:必需類型ArrayList<String>
提供Stream<People>
注意:我的解決方案必須使用流。 如何糾正我的解決方案以使其正常工作?
People
class定義:
public class People {
private String name;
private Double bankBalance;
private Integer numberOfCarsOwned;
public People(String name, Double bankBalance, Integer numberOfCarsOwned) {
this.name = name;
this.bankBalance = bankBalance;
this.numberOfCarsOwned = numberOfCarsOwned;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public Double getBankBalance() {
return bankBalance;
}
public void setBankBalance(Double bankBalance) {
this.bankBalance = bankBalance;
}
public Integer getNumberOfCarsOwned() {
return numberOfCarsOwned;
}
public void setNumberOfCarsOwned(Integer numberOfCarsOwned) {
this.numberOfCarsOwned = numberOfCarsOwned;
}
}
Crowd
class 定義:
public class Crowd {
private ArrayList<People> crowd;
public Crowd() {
this.crowd = new ArrayList<>();
}
public ArrayList<People> getCrowd() {
return crowd;
}
public void setCrowd(ArrayList<People> crowd) {
this.crowd = crowd;
}
public void addPeopleToCrowd(People people){
this.crowd.add(people);
}
public ArrayList<String> filterByLetterP(){
ArrayList<String> filteredNames = this.crowd.stream()
.filter(name -> name.getName().contains("P"));
return filteredNames;
}
}
有幾件事需要解決:
String#startsWith
而不是String#contains
。Stream
到People#name
。Stream
。如下圖所示:
public List<String> filterByLetterP() {
List<String> filteredNames = this.crowd.stream()
.map(p -> p.getName())
.filter(s -> s.startsWith("P"))
.collect(Collectors.toList());
return filteredNames;
}
您應該更改過濾器,因為它不會檢查以“P”開頭的名稱:
public List<String> filterByLetterP(){
return this.crowd.stream()
.map(People::getName)
.filter(name -> name.charAt(0) == 'P')
.collect(Collectors.toList());
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.