遍历List集合按照某属性分类放到Map
1 import com.google.common.collect.Maps; 2 import org.apache.commons.lang3.StringUtils; 3 4 import java.lang.reflect.Method; 5 import java.util.ArrayList; 6 import java.util.List; 7 import java.util.Map; 8 9 public class ListChangeMapUtils { 10 11 public static <T> Map<String, List<T>> objStringAndListToMapClassificationByName(List<T> list, String name) { 12 Map<String, List<T>> resultMap = Maps.newHashMap(); 13 for (T obj : list) { 14 try { 15 Method method = obj.getClass().getMethod("get" + name); 16 String keyName = (String) method.invoke(obj); 17 if (StringUtils.isBlank(keyName)) { 18 continue; 19 } 20 List<T> tempList = null; 21 if (!resultMap.containsKey(keyName)) { 22 tempList = new ArrayList<>(); 23 } else { 24 tempList = resultMap.get(keyName); 25 } 26 tempList.add(obj); 27 resultMap.put(keyName, tempList); 28 } catch (Exception e) { 29 30 } 31 } 32 return resultMap; 33 } 34 35 public static <T> Map<Long, List<T>> objLongAndListToMapClassificationByName(List<T> list, String name) { 36 Map<Long, List<T>> resultMap = Maps.newHashMap(); 37 for (T obj : list) { 38 try { 39 Method method = obj.getClass().getMethod("get" + name); 40 Long keyName = (Long) method.invoke(obj); 41 if (keyName == null) { 42 continue; 43 } 44 List<T> tempList = null; 45 if (!resultMap.containsKey(keyName)) { 46 tempList = new ArrayList<>(); 47 } else { 48 tempList = resultMap.get(keyName); 49 } 50 tempList.add(obj); 51 resultMap.put(keyName, tempList); 52 } catch (Exception e) { 53 54 } 55 } 56 return resultMap; 57 } 58 59 public static <T> Map<Integer, List<T>> objIntegerAndListToMapClassificationByName(List<T> list, String name) { 60 Map<Integer, List<T>> resultMap = Maps.newHashMap(); 61 for (T obj : list) { 62 try { 63 Method method = obj.getClass().getMethod("get" + name); 64 Integer keyName = (Integer) method.invoke(obj); 65 if (keyName == null) { 66 continue; 67 } 68 List<T> tempList = null; 69 if (!resultMap.containsKey(keyName)) { 70 tempList = new ArrayList<>(); 71 } else { 72 tempList = resultMap.get(keyName); 73 } 74 tempList.add(obj); 75 resultMap.put(keyName, tempList); 76 } catch (Exception e) { 77 78 } 79 } 80 return resultMap; 81 } 82 }