1. 程式人生 > >根據List中單個物件的某方法進行去重

根據List中單個物件的某方法進行去重

public static void main(String[] args){
		List<TQxtjEntity> list = new ArrayList<TQxtjEntity>();
		TQxtjEntity t1 = new TQxtjEntity("n1","1");
		TQxtjEntity t2 = new TQxtjEntity("n2","2");
		TQxtjEntity t3 = new TQxtjEntity("n2","2");
		TQxtjEntity t4 = new TQxtjEntity("n3","2");
		TQxtjEntity t5 = new TQxtjEntity("n1","3");
		TQxtjEntity t6 = new TQxtjEntity("n1","3");
		list.add(t1);
		list.add(t2);
		list.add(t3);
		list.add(t4);
		list.add(t5);
		list.add(t6);
		List<TQxtjEntity> li = removeRepeat(list,"com.kingtopinfo.qxgl.entity.TQxtjEntity","getName");
		System.out.println(li.size());
	}
	/**
	 * 根據oldList中單個物件的某方法進行去重
	 * @param oldList
	 * @param className
	 * @param methodName
	 * @return
	 */
	private static <T> List<T> removeRepeat(List<T> oldList,String classALLName,String methodName){
		try {
			//①找到類:
			Class cl = Class.forName(classALLName);
			//②建立物件(要求這個類中含有空引數的構造方法):
			Object obj = cl.newInstance();
			//③根據名稱和引數找方法:
			Method method1 = cl.getMethod(methodName);
			//④在某個物件上面執行方法,
			//Object result = method1.invoke(obj);
			
			List<T> newList = new ArrayList<T>();
			for(int i=0; i<oldList.size(); i++)
			{
				boolean tf = false;
				for(int j=0; j<newList.size(); j++){
					if(method1.invoke(newList.get(j)).equals(method1.invoke(oldList.get(i)))){
						tf = true;
						break;
					}
				}
				if(!tf){
					newList.add(oldList.get(i));
				}
			}
			return newList;
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return null;
	}