How to iterate over the vector in Java and store only the specified class?
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());
Wasn't anyone concerned about iterating the Vector without synchronization?
If vector
is not thread-confined, in the presence of another thread modifying its contents, the for-each iteration might throw ConcurrentModificationException
.