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

Pra*_*ede 2 java java-8

我有一个包含一些PersonObject 的列表.这是我的Person班级:

public class Person(){
// contructors 

private String lastname;

private String firstname;

private List<Place> places;

// getters and setters
}
Run Code Online (Sandbox Code Playgroud)

我的Place班级是:

public class Place(){
// contructors 

private String town;

// getters and setters
}
Run Code Online (Sandbox Code Playgroud)

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

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(???));
Run Code Online (Sandbox Code Playgroud)

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

怎么写这段代码?

War*_*ard 10

将方法hasPlace添加到Person类:

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

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

persons.removeIf(person -> person.hasPlace("Paris"));
Run Code Online (Sandbox Code Playgroud)


Era*_*ran 6

流式播放网上的名单Places,以确定它是否包含Placetown为"巴黎":

persons.removeIf(p-> p.getPlaces().stream().anyMatch(pl->pl.getTown().equals("Paris")));
Run Code Online (Sandbox Code Playgroud)

  • @Pracede`insities.removeIf()`只能从`persons``List`中删除`Person`实例.它不会改变它删除的元素,所以你描述的是不可能的. (2认同)