集合
1、List 转 Map
工具类代码
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
@Log4j2
public class CollectionUtils {
/**
* 将 List 集合转化为 Map, 可将 List 对象的任意字段当做 Map 的 key
* @param list 对象集合
* @param methodName 获取字段值的方法,比如 "getId"
* @param <V> key的类型,比如 Long
* @param <T> 对象类型,比如 User
* @return Map
*/
@SuppressWarnings("unchecked")
public static <V, T> Map<V, List<T>> listToListMap(List<T> list, String methodName){
Map<V, List<T>> map = new HashMap<>();
if (list.size() == 0){
return map;
}
try{
for (T obj : list) {
Method method = obj.getClass().getMethod(methodName);
V key = (V) method.invoke(obj);
if (map.get(key) == null){
List<T> objList = new ArrayList<T>();
objList.add(obj);
map.put(key, objList);
}else {
map.get(key).add(obj);
}
}
}catch (Exception exception){
log.error("List 转化为 Map 失败!");
}
return map;
}
}
使用示例
public static void main(String[] args) {
List<User> userList = new ArrayList<User>();
userList.add(new User(1L, "小明"));
userList.add(new User(1L, "小红"));
userList.add(new User(2L, "小明"));
userList.add(new User(3L, "小小"));
Map<Object, List<User>> idMap = CollectionUtils.listToMap(userList, "getId");
Map<Object, List<User>> usernameMap = CollectionUtils.listToMap(userList, "getUsername");
}
枚举
1、字典类型的枚举
示例
/**
* 中英字典
*/
public enum DictionaryEnum {
APPLE("苹果", "apple"),
BANANA("香蕉", "banana");
private String chinese;
private String english;
private static Map<String, String> enumMap = new HashMap<>();
static {
for (DictionaryEnum dictionaryEnum : DictionaryEnum.values()) {
enumMap.put(dictionaryEnum.chinese, dictionaryEnum.english);
}
}
DictionaryEnum(String chinese, String english){
this.chinese = chinese;
this.english = english;
}
public String getChinese() {
return chinese;
}
public String getEnglish() {
return english;
}
public static String getEnglishByChinese(String chinese){
String english = enumMap.get(chinese);
return english != null ? english : "";
}
}