testo
testo

Reputation: 1260

Collection for Objects and find them by the superclass

I need a Collection to store a couple of objects. I want to access them with there Class or Superclass.

For example: collection.get(Object.class) would return all Objects.

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

Upvotes: 3

Views: 285

Answers (3)

No, there is no built-in convenient way.

However, you could easily define a method 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.

Upvotes: 1

unique_ptr
unique_ptr

Reputation: 586

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

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

Upvotes: 1

Eran
Eran

Reputation: 394086

You can use Java 8 Streams for retrieving the required instances with a relatively short syntax. For example :

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

Of course such 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 that allows faster retrieval (perhaps HashMap).

Upvotes: 4

Related Questions