Home » Java » Java – Return set of all objects of certain type T where T is passed to the method

Java – Return set of all objects of certain type T where T is passed to the method

Posted by: admin October 18, 2018 Leave a comment

Questions:

I’m looking to write a method that given an original set A and a type T returns a new set containing all the objects of type T in A.

I’ve set up a test with a Person class and its subclasses Man and Woman, along with a World class to house the set of Person objects.

public class World {

    public World() {
        this.people = new HashSet<Person>();
    }

    public void addPerson(Person person) {
        getAllPeople().add(person);
    }

    public void removePerson(Person person) {
        getAllPeople().remove(person);
    }

    public Set<Person> getAllPeople() {
        return people;
    }

    public <T> Set<T> getAllPeople(Class<T> cls) {
        Set<T> ItemsOfClass = new HashSet<>();
        // Incompatible type error on next line
        ItemsOfClass = getAllPeople().stream().filter(object -> object.getClass().equals(cls)).collect(Collectors.toSet());
        return ItemsOfClass;
    }

    public Set<Person> people;
}

So I’d like getAllPeople(Man.class) to return a new set of Man objects.

My current implementation of getAllPeople is based on the following answers: https://stackoverflow.com/a/17840541 and
https://stackoverflow.com/a/16727596
although I can’t figure out how they are supposed to fit together, if at all.

I’m not good at generics so any and all explanation/advice is welcome.

Answers: