| 1234567891011121314151617181920212223242526272829 |
- package com.usky.config;
- import java.lang.reflect.Field;
- import java.util.ArrayList;
- import java.util.HashMap;
- import java.util.List;
- import java.util.Map;
- public class CollectionUtils {
- public CollectionUtils() {
- }
- public static <T> List<T> removeDuplicatesByField(List<T> list, String fieldName) throws NoSuchFieldException, IllegalAccessException {
- if (list != null && !list.isEmpty() && fieldName != null && !fieldName.isEmpty()) {
- Map<Object, T> map = new HashMap();
- for(T item : list) {
- Field field = item.getClass().getDeclaredField(fieldName);
- field.setAccessible(true);
- Object fieldValue = field.get(item);
- map.putIfAbsent(fieldValue, item);
- }
- return new ArrayList(map.values());
- } else {
- return list;
- }
- }
- }
|