Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to iterate over the vector in Java and store only the specified class?

Tags:

java

iterator

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.

like image 657
Ant's Avatar asked Dec 08 '12 14:12

Ant's


2 Answers

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);
        }
    }
like image 150
Parvin Gasimzade Avatar answered Oct 05 '22 02:10

Parvin Gasimzade


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());
like image 26
svarog Avatar answered Oct 05 '22 04:10

svarog