zoukankan      html  css  js  c++  java
  • list转map工具类,根据指定的字段分组


    import org.apache.log4j.Logger;

    import java.lang.reflect.Method;
    import java.util.ArrayList;
    import java.util.LinkedHashMap;
    import java.util.List;
    import java.util.Map;

    /**
    * list转map工具类,根据指定的字段分组
    *
    */
    public class EntryUtil {

    private static Logger logger = Logger.getLogger(EntryUtil.class);
    /**
    *
    * 将list中的元素放到Map<K, List<V>> 以建立 key - List<value> 索引<p>
    *
    * @param list List<V> 元素列表
    * @param keyFieldName String 元素的属性名称, 该属性的值作为索引key
    * @param <K> key类型
    * @param <V> value类型
    * @return Map<K, V> key - value 索引
    *
    *
    */
    public static <K, V> Map<K, List<V>> makeEntityListMap(List<V> list, String keyFieldName) {
    Map<K, List<V>> map = new LinkedHashMap<K, List<V>>();
    if(list == null || list.size() == 0) {
    return map;
    }
    try {
    Method getter = getMethod(list.get(0).getClass(), keyFieldName, "get");
    for (V item : list) {
    @SuppressWarnings("unchecked")
    K key = (K) getter.invoke(item);
    List<V> groupList = map.get(key);
    if (groupList == null) {
    groupList = new ArrayList<V>();
    map.put(key, groupList);
    }
    groupList.add(item);
    }
    } catch (Exception e) {
    logger.error("makeEntityListMap error list is " + list, e);
    return map;
    }
    return map;
    }

    /**
    * 获取getter或setter
    */
    @SuppressWarnings("unchecked")
    private static Method getMethod(@SuppressWarnings("rawtypes") Class clazz, String fieldName,
    String methodPrefix) throws NoSuchMethodException {
    String first = fieldName.substring(0, 1);
    String getterName = methodPrefix + fieldName.replaceFirst(first, first.toUpperCase());
    return clazz.getMethod(getterName);
    }
    }
  • 相关阅读:
    创建live usb
    gnome2.x面板(panel)或应用程序菜单误删后恢复
    grub & grub2
    linux(CentOS6)下的wifi热点安装配置------hostapd-2.0
    linux(Ubuntu)下的wifi热点安装配置------hostapd-2.0
    BZOJ3884 上帝与集合的正确用法(欧拉函数)
    Luogu4897 【模板】最小割树
    Contest 6
    BZOJ3811 玛里苟斯(线性基+概率期望)
    Contest 5
  • 原文地址:https://www.cnblogs.com/tom-plus/p/7923132.html
Copyright © 2011-2022 走看看