List集合去重,去除重复字段
public class ListDistinctUtils {
public static <T extends Student> List<T> distinctBySet01(List<T> oldList) {
Set<T> set = new TreeSet<>(new Comparator<T>() {
@Override
public int compare(T o1, T o2) {
return o1.getStuName().compareTo(o2.getStuName());
}
});
set.addAll(oldList);
return new ArrayList<>(set);
}
public static <T extends Student> List<T> distinctBySet02(List<T> oldList) {
Set<String> set = new HashSet<>();
List<T> newList = new ArrayList<>();
for (T t : oldList) {
if (!set.contains(t.getStuName())) {
set.add(t.getStuName());
newList.add(t);
}
}
return newList;
}
public static <T extends Student> List<T> distinctByMap(List<T> oldList) {
Map<String, Object> existMap = new HashMap<String, Object>();
List<T> newList = new ArrayList<>();
for (T t : oldList) {
String name = null != existMap.get(t.getStuName()) ? existMap.get(t.getStuName()).toString() : "";
if (StringUtils.isBlank(name)) {
existMap.put(t.getStuName(), t.getStuName());
newList.add(t);
}
}
return newList;
}
}