List求交并集并去重
直接看代码,主要用到了泛型,判断List反省中的东西是否相等,循环判断。
package com.sean.cloud.springcloud.test;
import java.beans.PropertyDescriptor;
import java.lang.reflect.Method;
import java.util.*;
public class UnionUtil {
/**
* 求交集并去重
* @param fieldName
* @param lists
* @param <T>
* @return
*/
public static <T> List<T> getIntersection(String fieldName,List<T>... lists){
List<T> result = new ArrayList<T>();
if(null != fieldName){
try{
Map<Object,T> map = new HashMap<Object, T>();
for (int i = 0; i < lists.length-1; i++) {
PropertyDescriptor propertyDescriptor = new PropertyDescriptor(fieldName, lists[i].get(0).getClass());
Method readMethod = propertyDescriptor.getReadMethod();
Map<Object, T> temp = new HashMap<Object, T>();
for (T li : lists[i]) {
map.put(readMethod.invoke(li), li);
}
for (T li : lists[i+1]) {
Object key = readMethod.invoke(li);
if (map.containsKey(key)) {
temp.put(key, li);
}
}
for (Object key : temp.keySet()) {
result.add(temp.get(key));
}
}
}catch(Exception e){
e.printStackTrace();
return null;
}
}else{
for (int i = 0; i < lists.length-1; i++) {
Set<T> set1 = new HashSet<>(lists[i]);
Set<T> set2 = new HashSet<>(lists[i+1]);
for(T li : set2){
if(set1.contains(li)){//求交集
Set<T> set3 = new HashSet<>(result);
if(!result.contains(li)){
result.add(li);
}
}
}
}
}
return result;
}
/**
* 求并集去重
* @param list1
* @param list2
* @param fieldName
* @param <T>
* @return
*/
public static <T> List<T> getUnion(List<T> list1,List<T> list2,String fieldName) {
list1.addAll(list2);
if(null != fieldName){//对象
Map<Object,T> map = new HashMap<Object, T>();
List<T> list = new ArrayList<T>();
try{
PropertyDescriptor propertyDescription = new PropertyDescriptor(fieldName, list1.get(0).getClass());
Method readMethod = propertyDescription.getReadMethod();
for(T li : list1){//根据某属性值去重
Object fieldValue = readMethod.invoke(li);
map.put(fieldValue, li);
}
}catch(Exception e){
e.printStackTrace();
return null;
}
for(Object key : map.keySet()){
list.add(map.get(key));
}
return list;
}else{//基本类型
Set<T> set = new HashSet<>(list1);
return new ArrayList<T>(set);
}
}
}