Splits a collection of any object into a map of the provided field value and collection. - Java java.util

Java examples for java.util:Collection Element

Description

Splits a collection of any object into a map of the provided field value and collection.

Demo Code


import java.lang.reflect.Array;
import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.Collections;
import java.util.Comparator;
import java.util.HashMap;
import java.util.LinkedHashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;

public class Main{
    public static void main(String[] argv){
        List items = java.util.Arrays.asList("asdf","book2s.com");
        String fieldName = "book2s.com";
        System.out.println(splitByField(items,fieldName));
    }/*w w  w.  j a v  a  2 s.c  om*/
    /**
     * Splits a collection of any object into a map of the provided field value
     * and collection.
     * 
     * @param <T>
     * @param items
     * @param fieldName
     *            (Must have to have get-set methods in T)
     * @return
     */
    public static <T, V extends Comparable<V>> Map<V, List<T>> splitByField(
            List<T> items, String fieldName) {
        Map<V, List<T>> splittedMap = new HashMap<V, List<T>>();

        if (null != items) {
            FieldSpecificComparator<T, V> comparator = new FieldSpecificComparator<T, V>(
                    fieldName);
            Collections.sort(items, comparator);
            for (int i = 0; i < items.size(); i++) {
                T item = items.get(i);
                Class<T> clazz = (Class<T>) item.getClass();
                Method[] methods = clazz.getDeclaredMethods();
                V value = null;
                String getterMethodName = "get" + fieldName;
                for (Method method : methods) {
                    if (method.getName().startsWith("get")) {
                        if (method.getName().equalsIgnoreCase(
                                getterMethodName)) {
                            try {
                                value = (V) method.invoke(item, null);
                            } catch (Exception e) {
                                e.printStackTrace();
                            }
                            break;
                        }
                    }
                }
                if (splittedMap.get(value) == null) {
                    List<T> list = new ArrayList<T>();
                    splittedMap.put(value, list);
                }

                List<T> list = splittedMap.get(value);
                list.add(items.remove(i));
                i--;
            }
        }

        return splittedMap;
    }
}

Related Tutorials