工具类15:BeanMapper

/*******************************************************************************
 * Copyright (c) 2005, 2014 springside.io
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 *******************************************************************************/
package com.meallink.core.comm;

import com.google.common.collect.Lists;
import com.google.common.collect.Maps;
import ma.glasnost.orika.MapperFacade;
import ma.glasnost.orika.MapperFactory;
import ma.glasnost.orika.impl.DefaultMapperFactory;

import java.util.List;
import java.util.Map;
import java.util.function.Function;
//import ma.glasnost.orika.impl.generator.EclipseJdtCompilerStrategy;

/**
 * 简单封装orika, 实现深度转换Bean<->Bean的Mapper.
 */
public class BeanMapper {

    private static MapperFacade mapper = null;

    static {
        MapperFactory mapperFactory = new DefaultMapperFactory.Builder().build();
//      MapperFactory mapperFactory = 
//              new DefaultMapperFactory.Builder()
//                      .compilerStrategy(new EclipseJdtCompilerStrategy())
//                      .build();
        mapper = mapperFactory.getMapperFacade();

    }

    /**
     * 基于Dozer转换对象的类型.
     */
    public static  D map(S source, Class destinationClass) {
        return mapper.map(source, destinationClass);
    }

    /**
     * 基于Dozer转换Collection中对象的类型.
     */
    public static  List mapList(Iterable sourceList, Class destinationClass) {
        return mapper.mapAsList(sourceList, destinationClass);
    }

    /**
     * 集合转map
     *
     * @param sourceList 集合
     * @param IMapKey    getkey方法
     * @param         集合对像类型
     * @param         key类型
     * @return
     */
    public static  Map toMap(Iterable sourceList, Function IMapKey) {
        Map result = Maps.newHashMap();
        if (sourceList == null) {
            return result;
        }
        for (D d : sourceList) {
            result.put(IMapKey.apply(d), d);
        }
        return result;
    }

    /**
     * 集合转map
     *
     * @param sourceList 集合
     * @param IMapKey    getkey方法
     * @param         集合对像类型
     * @param         key类型
     * @return
     */
    public static  Map> toMapList(Iterable sourceList, Function IMapKey) {
        Map> result = Maps.newHashMap();
        if (sourceList == null) {
            return result;
        }
        for (D d : sourceList) {
            S key = IMapKey.apply(d);
            if (result.containsKey(key)) {
                List list = result.get(key);
                list.add(d);
            } else {
                List list = Lists.newArrayList();
                list.add(d);
                result.put(key, list);
            }
        }
        return result;
    }
}

记录一个数据处理的工具类,天天用离不开

你可能感兴趣的:(工具类15:BeanMapper)