利用java8特性实现集合类中对象元素转换类型

import java.util.ArrayList;
import java.util.Collection;
import java.util.List;
import java.util.stream.Collectors;
import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.collection.CollectionUtil;
import lombok.Data;

/**
 * (描述这个类的作用)
 * @author STRX-LZY
 * @date 2019年9月6日
 *
 */
public class CollectionUtils extends CollectionUtil
{
	/**
	 * 
	 * 描述这个方法的作用
	 * @author STRX-LZY
	 * @date 2019年9月6日
	 * @param collection
	 * @param clazz
	 * @return
	 */
	public static <T> Collection<T> coventObject(Collection<?> collection, Class<T> clazz)
	{
		Collection<T> newCollection = collection.stream().map(oldObject -> {
			T instance = null;
			try
			{
				instance = clazz.newInstance();
			}
			catch (Exception e)
			{
				e.printStackTrace();
			}
			BeanUtil.copyProperties(oldObject, instance);
			return instance;
		}).collect(Collectors.toList());
		return newCollection;
	};

	public static void main(String[] args)
	{
		ArrayList<A> a = CollectionUtil.newArrayList(new A("a", "b"), new A("aa", "bb"));
		List<B> b = (List<B>) CollectionUtils.coventObject(a, B.class);
		System.out.println(b.get(1).getA());
	}

}

@Data
class A
{
	private String a;
	private String b;

	public A(String a, String b)
	{
		super();
		this.a = a;
		this.b = b;
	}
}

@Data
class B
{
	private String a;
	private String c;

	public B(String a, String c)
	{
		super();
		this.a = a;
		this.c = c;
	}

	public B()
	{
	}

}

你可能感兴趣的:(java)