Java 自写工具类积累

集合

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            key的类型,比如 Long
     * @param            对象类型,比如 User
     * @return  Map
     */
    @SuppressWarnings("unchecked")
    public static  Map> listToListMap(List list, String methodName){
        Map> 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 objList = new ArrayList();
                    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 userList = new ArrayList();
        userList.add(new User(1L, "小明"));
        userList.add(new User(1L, "小红"));
        userList.add(new User(2L, "小明"));
        userList.add(new User(3L, "小小"));
        Map> idMap = CollectionUtils.listToMap(userList, "getId");
        Map> usernameMap = CollectionUtils.listToMap(userList, "getUsername");
 
    }

枚举

1、字典类型的枚举

示例

/**
 * 中英字典
 */
public enum DictionaryEnum {

    APPLE("苹果", "apple"),
    BANANA("香蕉", "banana");

    private String chinese;

    private String english;

    private static Map 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 : "";
    }

}

你可能感兴趣的:(Java 自写工具类积累)