2

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?

Mark Rotteveel
  • 100,966
  • 191
  • 140
  • 197
Pracede
  • 4,226
  • 16
  • 65
  • 110

3 Answers3

10

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"));
Ward
  • 2,799
  • 20
  • 26
  • Thank yo for your answer. I tried it but it just removes places from person and not the person which place is Paris. Am i miss something ? – Pracede Dec 27 '17 at 13:56
  • 1
    What you say is not possible: this code will only READ places from a person, and shouldn't ouch anything. Maybe you can post your complete code to check? – Ward Dec 27 '17 at 15:51
6

Stream over the list of Places to determine if it contains a Place whose town is "Paris":

persons.removeIf(p-> p.getPlaces().stream().anyMatch(pl->pl.getTown().equals("Paris")));
Eran
  • 387,369
  • 54
  • 702
  • 768
  • Why not do: collectionName.removeIf(x -> x.getName().equals(name_to_compare)); ? – whatamidoingwithmylife Dec 27 '17 at 12:35
  • @GCP Because the `Person` class doesn't contain the name you have to compare to "Paris". You have to check the `getPlaces()` list for instances of `Places` that contain the town "Paris". – Eran Dec 27 '17 at 12:37
  • I just noticed there is only one field in that class. My bad. – whatamidoingwithmylife Dec 27 '17 at 12:40
  • Thank yo for your answer. I tried it but it just removes places from person and not the person which place is Paris. Am i miss something ? – Pracede Dec 27 '17 at 14:39
  • 2
    @Pracede `persons.removeIf()` can only remove `Person` instance from the `persons` `List`. It does not mutate the elements it removes, so what you describe is not possible. – Eran Dec 27 '17 at 14:42
0

If you don't want to use removeIf method, you could use Filter to

persons.stream().filter(p-> !p.getPlaces().stream().anyMatch(pl->pl.getTown().equals("Paris")));
GuyKhmel
  • 505
  • 5
  • 15