zoukankan      html  css  js  c++  java
  • List -> Map 工具类,list转为map

    提供了List转为Map的2种方法,第一种convertOne是常规转换,以key作为map的key,以list中的E作为value;第二种则以key作为map的key,以list作为value


    @SuppressWarnings("unchecked") final public class MapConverter { private static final String GET = "get"; private MapConverter() { throw new AssertionError("Util禁止反射实例化"); } public static <K, E> Map<K, E> convertOne(List<E> list, String key) { if (CollectionUtils.isEmpty(list)) { return null; } Map<K, E> map = null; try { Method getM = getMethod(list.get(0).getClass(), key); map = new HashMap<>(); for (E en : list) { K k = (K) getM.invoke(en); map.put(k, en); } } catch (Exception e) { e.printStackTrace(); } return map; } public static <K, E> Map<K, List<E>> convertList(List<E> list, String key) { if (CollectionUtils.isEmpty(list)) { return null; } Map<K, List<E>> map = null; try { Method getM = getMethod(list.get(0).getClass(), key); map = new HashMap<>(); for (E en : list) { K k = (K) getM.invoke(en); List<E> res = map.get(k); if (res != null) { res.add(en); } else { List<E> l1 = new ArrayList<>(); l1.add(en); map.put(k, l1); } } } catch (Exception e) { e.printStackTrace(); } return map; } private static Method getMethod(Class clazz, String key) throws NoSuchMethodException { if (key.startsWith(GET)) { return clazz.getMethod(key); } if (Character.isUpperCase(key.charAt(0))) { clazz.getMethod(GET + key); } return clazz.getMethod(GET + Character.toUpperCase(key.charAt(0)) + key.substring(1)); } }
  • 相关阅读:
    GridView自定义分页
    intro
    ListView和DataPager初试
    在DataGrid中,如何录入数量及单价的时候自动算出金额
    常用正则表达式
    ASP.NET中基类页的设计和使用
    Asp.net实现无刷新检测用户名
    在asp.net2.0中使用存储过程
    .NET中的抽象工厂
    用C#生成随机中文汉字验证码的基本原理 [转]
  • 原文地址:https://www.cnblogs.com/zad27/p/10991138.html
Copyright © 2011-2022 走看看