提供了 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));
- }
- }
来源: http://www.bubuko.com/infodetail-3086437.html