Collection for objects and find them in superclass

I need a collection to store multiple objects. I want to access them there Class or Superclass.

For example: collection.get(Object.class)

returns all objects.

Is there a ready-made class that I can use or do I need to write myself. In this case, I would use a base HashMap<Class,Object>

.

+3
java collections


source to share


3 answers


You can use Java 8 streams to fetch the required instances with relatively short syntax. For example:

List<SomeType> objects = collections.filter(o -> o instanceof SomeType).collect(Collectors.toList());

      



Of course, this kind of code requires iterating over your entire Collection. If the collection is large and performance is an issue, you should probably store your objects in some data structure, which makes searching faster (maybe HashMap

).

+4


source to share


If you are using java 8 consider the previous post else solution, you can use apache



 CollectionUtils.filter( youList, new Predicate(){
     public boolean evaluate( Object input ) {
        return input instanceof youClass;
     }
  } );

      

+1


source to share


No, there is no convenience way built in.

However, you can easily figure out how to do it:

<T> List<T> getAllElements(Collection<?> collection, Class<T> targetClass) {
    List<T> result = new ArrayList<T>();
    for(Object obj : collection)
        if(targetClass.isInstance(obj))
            result.add(targetClass.cast(obj));
    return result;
}

      

This is essentially the same as Eran's lambda solution, but without using Java 8 features.

+1


source to share







All Articles
Loading...
X
Show
Funny
Dev
Pics