Java 按照多個字段對集合去重

import java.lang.reflect.InvocationTargetException; import java.lang.reflect.Method; import java.util.ArrayList; import java.util.Comparator; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.Set; import java.util.TreeSet;java

public class JavaUtil {code

public static <T> List<T> filterList(List<T> list,String... args){
	//若是沒有數據,無需去重
	if (null == list || list.isEmpty()){
		return new ArrayList<T>();
	}
	
	//set集合去重複
	Set<T> set = new TreeSet<T>(new Comparator<T>() {
		@SuppressWarnings({ "unchecked", "rawtypes" })
		public int compare(T o1, T o2) {
			Class clazz1 = o1.getClass();
			Class clazz2 = o2.getClass();
			Method mv1;
			Method mv2;
			try {
				//比較參數的個數
				//int size = args.length;
				int result = 0;
				for (String gets : args){
					mv1 = clazz1.getDeclaredMethod(gets);
					mv2 = clazz2.getDeclaredMethod(gets);
					String argVal = null == mv1.invoke(o1) ? "" : mv1.invoke(o1) + "";
					String argVa2 = null == mv2.invoke(o2) ? "" : mv2.invoke(o2) + "";
					result = argVal.compareTo(argVa2);
					if (result != 0){
						break;
					} 
				}
				return result;
			} catch (NoSuchMethodException e) {
				e.printStackTrace();
			} catch (SecurityException e) {
				e.printStackTrace();
			} catch (IllegalAccessException e) {
				e.printStackTrace();
			} catch (IllegalArgumentException e) {
				e.printStackTrace();
			} catch (InvocationTargetException e) {
				e.printStackTrace();
			}
			
			return 0;
		}
	});
	
	set.addAll(list);
	return new ArrayList<T>(set);
}

}get

相關文章
相關標籤/搜索