集合转map

public class ConvertUtil {

    private ConvertUtil() {
    }

    public static <T, R> List<R> resultToList(List<T> originList, Function<T, R> mapper) {
        if (originList == null || originList.isEmpty()) {
            return new ArrayList<>();
        }
        List<R> resultList = new ArrayList<>();
        for (T originElement : originList) {
            R newElement = mapper.apply(originElement);
            if (newElement == null) {
                continue;
            }
            resultList.add(newElement);
        }
        return resultList;
    }


    public static <V, K> Map<K, V> listToMap(List<V> originList, Function<V, K> keyExtractor) {
        if (originList == null || originList.isEmpty()){
            return new HashMap<>();
        }
        Map<K, V> result = new HashMap<>();
        for (V element : originList){
            K key = keyExtractor.apply(element);
            result.put(key, element);
        }
        return result;
    }
}


posted @ 2022-06-13 11:04  紫川先生  阅读(70)  评论(0编辑  收藏  举报