I have a use case where I need to iterate over the Vector
elements and store the results in say array only if that instance is of class method
Are there any easy to do this?
Currently I'm doing this way :
Iterator itr = vec.iterator();
Iterator element = vec.iterator();
while(itr.hasNext())
{
boolean method = itr.next() instanceof Method;
if(method)
System.out.println( "\t" + ( (Method)(element.next()) ).name);
else
element.next();
}
But I think there will be some better way than this.
Assume you have a class Method
, then code could be something like :
List<Method> list = new ArrayList<Method>();
for (Object obj : vector) {
if (obj instanceof Method) {
list.add(obj);
}
}
In Java 8, you can invoke the .stream()
method that returns a stream of the vector elements, so storing the elements, for example in a list, can be done by invoking a Collector
Vector<String> vec = new Vector<>();
vec.add("hello");
vec.add("world");
List<String> list = vec.stream().collect(Collectors.toList());
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With