简体   繁体   English

Java-返回特定类型T的所有对象的集合,其中T传递给方法

[英]Java - Return set of all objects of certain type T where T is passed to the method

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. 我正在寻找一种方法,该方法给定原始集合A,类型T返回一个新集合,该集合包含A中所有类型T的对象。

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. 我已经建立了一个Person类及其子类ManWoman以及World类的测试,以容纳Person对象集。

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. 因此,我希望getAllPeople(Man.class)返回一组新的Man对象。

My current implementation of getAllPeople is based on the following answers: https://stackoverflow.com/a/17840541 and 我目前对getAllPeople实现基于以下答案: https : //stackoverflow.com/a/17840541
https://stackoverflow.com/a/16727596 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. 我不太擅长泛型,因此欢迎您提供任何解释/建议。

You have to cast your element inside stream first: 您必须先将元素转换为流:

public <T> Set<T> getAllPeople(Class<T> clazz) {
    return obj.stream().filter(object -> object.getClass().equals(clazz))
              .map(v -> (T) v).collect(Collectors.toSet());
}

Here the problem is very probably the assignment : 这里的问题很可能是作业:

 ItemsOfClass = getAllPeople().stream().filter(object -> object.getClass().equals(T)).collect(Collectors.toSet());

The created Set by the collect() method is not typed as Set<T> even if you filtered only object which the class is T . 即使仅过滤了类为T对象,也未将collect()方法创建的Set键入为Set<T>
Actually you iterate on Person . 实际上,您在Person进行迭代。 So you collect a Set<Person> 所以你收集一个Set<Person>
So you are constraint to cast explicitly Set<Person> to Set<T> such as : 因此,您必须将Set<Person>显式转换为Set<T>例如:

 ItemsOfClass = (Set<T>) getAllPeople().stream()
                                       .filter(object -> object.getClass().equals(T))
                                       .collect(Collectors.toSet());

or with Class::cast such as : 或使用Class::cast如:

 ItemsOfClass =  getAllPeople().stream()
                              .filter(object -> object.getClass().equals(T))
                              .map(T::cast)
                              .collect(Collectors.toSet());

You have a Stream<Person> that you are trying to collect into a Set<T> . 您有一个Stream<Person>试图收集到Set<T> But a Stream<Person> will produce a Set<Person> . 但是Stream<Person>将产生Set<Person>

You can map your Person instances to T instances and get a Stream<T> . 您可以将Person实例映射到T实例,并获得Stream<T>

public <T> Set<T> getAllPeople(Class<T> cls) {
    Set<T> itemsOfClass = getAllPeople().stream()
              .filter(cls::isInstance)
              .map(cls::cast)
              .collect(Collectors.toSet());
    return itemsOfClass;
}

This uses cls::isInstance as a predicate to find elements of the class cls , and cls::cast as a mapper to regard your elements as T instances instead of Person instances. 这使用cls::isInstance作为谓词来查找类cls元素,并使用cls::cast作为映射器,将您的元素视为T实例而不是Person实例。

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

相关问题 返回类型之前的通用方法java 6 <T> - Generic method java 6 <T> before return type 更改Java中特定类型的所有对象的属性 - Change attributes of all objects of a certain type in Java 在调用接受Class <T>并返回T的泛型方法时,如何返回某个类型的列表? - How can I return a list of a certain type when calling a generic method that accepts a Class<T> and returns a T? java泛型方法的返回类型应该与传递的传递参数相同 - java generics return type of method should be same pass parameter passed 对特定类型的所有对象的Java调用方法 - Java calling method on all objects of specific type Java 泛型,返回 T 的方法,其中<T extends String>不能返回字符串 - Java generic, method that returns T where <T extends String> cannot return string 如何在Java中为方法设置特定的返回类型 - How to set a specific return type to a method in Java Java:方法返回 Class<t> (在哪里<t extends basetype> )。 返回子类 class 导致类型不匹配错误</t></t> - Java: Method returns Class<T> (where <T extends BaseType>). Returning subclass class causes type mismatch error 为什么呢 <T> 在Java Generics中键入`作为返回类型而不是`Type <T> `? - Why is it `<T>Type` as return type in Java Generics and not `Type<T>`? Java 泛型类型非静态方法返回 Object 而不是泛型类型 T - Java Generic Type non-static method return Object instead of generic type T
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM