Java tutorial
//package com.java2s; /* * Copyright (C) 2002-2015 FlyMine * * This code may be freely distributed and modified under the * terms of the GNU Lesser General Public Licence. This should * be distributed with the code. See the LICENSE file for more * information or http://www.gnu.org/copyleft/lesser.html. * */ import java.util.ArrayList; import java.util.Collection; import java.util.HashMap; import java.util.HashSet; import java.util.List; import java.util.Map; import java.util.Set; import java.util.Stack; public class Main { /** * Sorts objects in the given collection into different types by Class. * @param <E> the element type * @param objects a Collection of objects * @param inherit if true, objects are put into all their class's superclasses as well, except * Object - the original Collection can be used in that case * @return a Map from Class to List of objects in that class */ public static <E> Map<Class<?>, List<E>> groupByClass(Collection<E> objects, boolean inherit) { Map<Class<?>, List<E>> retval = new HashMap<Class<?>, List<E>>(); for (E o : objects) { Class<?> c = o.getClass(); if (inherit) { Set<Class<?>> done = new HashSet<Class<?>>(); done.add(Object.class); Stack<Class<?>> todo = new Stack<Class<?>>(); todo.push(c); while (!todo.empty()) { c = todo.pop(); if ((c != null) && !done.contains(c)) { done.add(c); List<E> l = retval.get(c); if (l == null) { l = new ArrayList<E>(); retval.put(c, l); } l.add(o); todo.push(c.getSuperclass()); Class<?>[] classes = c.getInterfaces(); for (int i = 0; i < classes.length; i++) { todo.push(classes[i]); } } } } else { List<E> l = retval.get(c); if (l == null) { l = new ArrayList<E>(); retval.put(c, l); } l.add(o); } } return retval; } }