I have a list with some Person
Object. Here is my Person
class:
public class Person(){
// contructors
private String lastname;
private String firstname;
private List<Place> places;
// getters and setters
}
My Place
class is :
public class Place(){
// contructors
private String town;
// getters and setters
}
I have code to remove some places from person:
List<Person> persons = new ArrayList<Person>();
// adding persons to List
// Below i want to remove person whose place is in town Paris.
persons.removeIf((Person person)-> person.getPlaces(???));
I want to remove a person from the list whose Place
meets the following condition place.getTown()=="Paris"
How to write this code?
Add a method hasPlace to Person class:
public boolean hasPlace(String townName) {
return places.stream()
.map(Place::getTown)
.anyMatch(townName::equals);
}
Then, you can use this in the predicate given to the removeIf statement:
persons.removeIf(person -> person.hasPlace("Paris"));
流式播放网上的名单Places
,以确定它是否包含一个Place
,其town
是“巴黎”:
persons.removeIf(p-> p.getPlaces().stream().anyMatch(pl->pl.getTown().equals("Paris")));
如果您不想使用removeIf方法,可以使用Filter to
persons.stream().filter(p-> !p.getPlaces().stream().anyMatch(pl->pl.getTown().equals("Paris")));
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.