Returns a list containing all of the elements of a certain class contained in a collection. - Java java.util

Java examples for java.util:Collection to List

Description

Returns a list containing all of the elements of a certain class contained in a collection.

Demo Code


//package com.java2s;

import java.util.ArrayList;
import java.util.Collection;
import java.util.Iterator;
import java.util.List;

public class Main {
    public static void main(String[] argv) {
        Collection c = java.util.Arrays.asList("asdf", "java2s.com");
        Class cla = String.class;
        System.out.println(getElementsByClass(c, cla));
    }//  ww  w. j  ava 2s.  c o m

    public static List getElementsByClass(Collection c, Class cla) {
        List r = new ArrayList();

        if (c == null || cla == null || c.isEmpty())
            return r;

        for (Iterator i = c.iterator(); i.hasNext();) {
            Object o = i.next();

            if (o.getClass() == cla)
                r.add(o);
        }

        return r;
    }
}

Related Tutorials