package com.yanzuoguang.util.helper; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; public class MapHelper { /** * 将一个对象列表转换为HashMap * * @param list 需要转换的列表 * @param <T> * @return */ public static <T extends MapKey> Map<String, T> getMap(List<T> list) { Map<String, T> map = new HashMap<>(); if (list != null) { for (T item : list) { String key = item.getKey(item); map.put(key, item); } } return map; } /** * 将一个对象列表转换为HashMap * * @param list 需要转换的列表 * @param proxy 获取主键的函数 * @param <T> * @return */ public static <T extends Object> Map<String, T> getMap(List<T> list, MapKey<T> proxy) { Map<String, T> map = new HashMap<>(); if (list != null) { for (T item : list) { String key = proxy.getKey(item); map.put(key, item); } } return map; } /** * 将一个对象列表转换为HashMap * * @param list 需要转换的列表 * @param <T> * @return */ public static <T extends MapKey> List<String> getKeys(List<T> list) { List<String> to = new ArrayList<>(); if (list != null) { for (T item : list) { String key = item.getKey(item); if (!to.contains(key)) { to.add(key); } } } return to; } /** * 将一个对象列表转换为HashMap * * @param list 需要转换的列表 * @param proxy 获取主键的函数 * @param <T> * @return */ public static <T extends Object> List<String> getKeys(List<T> list, MapKey<T> proxy) { List<String> to = new ArrayList<>(); if (list != null) { for (T item : list) { String key = proxy.getKey(item); if (!to.contains(key)) { to.add(key); } } } return to; } /** * 一个获取对象关键字的处理函数 * * @param <T> */ public interface MapKey<T> { String getKey(T from); } /** * 将建添加到子数组中 * * @param mapList * @param key * @param item * @param <T> * @param <M> * @return */ public static <T, M> List<M> addMapList(Map<T, List<M>> mapList, T key, M item) { if (!mapList.containsKey(key)) { mapList.put(key, new ArrayList<>()); } List<M> ret = mapList.get(key); ret.add(item); return ret; } }