Skip to content
Advertisement

Check if items in List match with String attribute in list of objects

Let’s say I have a list of names:

List<String> names = new ArrayList<>();
names.add("Paul");
names.add("Jeff");
names.add("Anna");

On the other hand, I have a list of people:

List<Person> people = new ArrayList<>();
people.add( new Person("Paul", 30) );
people.add( new Person("Jeff", 50) );

Person has name and age attributes. From the first list of names, I need to know what names are not present as names in the list of people. This is my attempt:

    List<String> namesNotPresent = new ArrayList<>();
    for (String name : names) {
        boolean nameNotPresent = people.stream()
                .noneMatch(p -> name.equals(p.getName()));
        if (nameNotPresent) {
            namesNotPresent.add(name);
        }
    }

I wonder if there is a better approach, a more functional one, and I also wonder if the list of people should be ordered?

This is working for me though. I don’t expect the list of names and people to be a huge list, there might be exceptions where they could have around 1000 items though.

Advertisement

Answer

public List<String> findNameNotPresent(List<String> names, List<Person> people) {
    List<String> result = new ArrayList<>(names);
    people.stream()
        .map(Person::getName)
        .forEach(result::remove);
    return result;
}
User contributions licensed under: CC BY-SA
1 People found this is helpful
Advertisement