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>
.
source to share
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
).
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.
source to share