java
复制代码
package com.zhongma.people.car.fitting.tool;
import com.zhongma.people.car.fitting.bean.FittingResult;
import com.zhongma.people.car.fitting.core.BeanStore;
import org.springframework.util.ObjectUtils;
import java.lang.reflect.Field;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Iterator;
import java.util.List;
/**
* @author konglcwqy
* @description 对象工具类
* @date 2023/8/21 10:05
*/
public class BeanTool {
/**
* 功能描述:对象属性值比较
*
* @param me
* @param target
* @param fields
* @return boolean
* @author konglcwqy
* @date 2023/8/21 10:07
*/
public static <T> boolean equal(T me, T target, String... fields) throws Exception {
if (fields == null || fields.length == 0) {
throw new Exception("field is null");
}
List<String> list = Arrays.asList(fields);
Field[] declaredFields = me.getClass().getDeclaredFields();
if (declaredFields == null || declaredFields.length == 0) {
return true;
}
Object me_value = null;
Object target_value = null;
for (Field declaredField : declaredFields) {
if (list.contains(declaredField.getName())) {
declaredField.setAccessible(true);
me_value = declaredField.get(me);
target_value = declaredField.get(target);
if (!ObjectUtils.nullSafeEquals(me_value, target_value)) {
return false;
}
}
}
return true;
}
/**
* 功能描述:集合去重
*
* @param list
* @param fields
* @return java.util.List<T>
* @author konglcwqy
* @date 2023/8/21 10:33
*/
public static <T> List<T> beanListDistinct(List<T> list, String... fields) throws Exception {
List<T> result = new ArrayList<T>();
Iterator<T> iterator = null;
boolean flag = false;
T me;
out:
for (T target : list) {
iterator = result.iterator();
inner:
while (iterator.hasNext()) {
me = iterator.next();
if (equal(me, target, fields)) {
continue out;
}
}
result.add(target);
}
return result;
}
public static void main(String[] args) throws Exception {
FittingResult fittingResult1 = new FittingResult("1", 1, "a", 100, BeanStore.WEAK_BING);
FittingResult fittingResult2 = new FittingResult("1", 1, "a", 100, BeanStore.WEAK_BING);
FittingResult fittingResult3 = new FittingResult("1", 1, "a", 100, BeanStore.WEAK_BING);
FittingResult fittingResult4 = new FittingResult("1", 1, "a", 100, BeanStore.WEAK_BING);
FittingResult fittingResult5 = new FittingResult("1", 1, "b", 90, BeanStore.WEAK_BING);
FittingResult fittingResult6 = new FittingResult("1", 1, "b", 90, BeanStore.WEAK_BING);
FittingResult fittingResult7 = new FittingResult("1", 1, "b", 90, BeanStore.WEAK_BING);
FittingResult fittingResult8 = new FittingResult("1", 1, "b", 90, BeanStore.WEAK_BING);
List<FittingResult> list = new ArrayList<FittingResult>();
list.add(fittingResult1);
list.add(fittingResult2);
list.add(fittingResult3);
list.add(fittingResult4);
list.add(fittingResult5);
list.add(fittingResult6);
list.add(fittingResult7);
list.add(fittingResult8);
list = beanListDistinct(list, "eventId", "eventType", "carNum");
System.out.println(list.size());
}
}