繁体   English   中英

如果他的列表符合条件,如何使用Collection删除?

[英]How to use Collection remove if his list meet a condition?

我有一个包含一些Person Object的列表。 这是我的Person类:

public class Person(){
// contructors 

private String lastname;

private String firstname;

private List<Place> places;

// getters and setters
}

我的Place课程是:

public class Place(){
// contructors 

private String town;

// getters and setters
}

我有代码从人删除一些地方:

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(???));

我想从列表中删除一个人符合以下条件的Place place.getTown()=="Paris"

怎么写这段代码?

将方法hasPlace添加到Person类:

public boolean hasPlace(String townName) {
    return places.stream()
            .map(Place::getTown)
            .anyMatch(townName::equals);
}

然后,您可以在给予removeIf语句的谓词中使用它:

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")));

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM