Given a List of objects, convert the values it contains to the passed in Map. - Java java.util

Java examples for java.util:Map Key

Description

Given a List of objects, convert the values it contains to the passed in Map.

Demo Code

/*//from   w  w w  . j  av a  2s.c  o  m
 * Copyright 2006 - Gary Bentley
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
import java.util.Map;
import java.util.List;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.Arrays;
import java.lang.reflect.InvocationTargetException;

public class Main{
    /**
     * Given a List of objects, convert the values it contains to the passed in Map.
     * The <b>keyAccessor</b> and <b>valueAccessor</b> parameters should
     * be {@link Getter accessors} and specify the key and value for the
     * map respectively.  Set <b>valueAccessor</b> to <code>null</code> to mean that
     * the object from the List should be added as the value.  Note: all the objects
     * in the list MUST be of the same type, to determine the class the first object
     * in the list is examined.
     *
     * @param objs The objects to convert.
     * @param map The Map to add the objects to.
     * @param keyAccessor The accessor for the key to set in the map.
     * @param valueAccessor The accessor for the value to set in the map, set to <code>null</code>
     *                      to get the object added.
     */
    public static void convertListToMap(List objs, Map map,
            String keyAccessor, String valueAccessor)
            throws IllegalAccessException, InvocationTargetException,
            ClassCastException {

        if ((objs == null) || (map == null)) {

            return;

        }

        if (objs.size() == 0) {

            return;

        }

        Class c = objs.get(0).getClass();

        Getter ka = new Getter(keyAccessor, c);
        Getter va = null;

        if (valueAccessor != null) {

            va = new Getter(valueAccessor, c);

        }

        for (int i = 0; i < objs.size(); i++) {

            Object o = objs.get(i);

            Object k = ka.getValue(o);

            Object v = null;

            if (va == null) {

                v = o;

            } else {

                v = va.getValue(o);

            }

            map.put(k, v);

        }

    }
}

Related Tutorials