sql中去重可以使用distinct关键字,但是有时候需要在list中去重,大概有以下几种方式
1.嵌套for循环去重
因为list删除一个元素会让后面的元素前移,所以可以倒着删除,也可以使用迭代器
for (int i = projectList.size() - 1; i >= 0; i--) { for (int j = projectList.size() - 1; j >= 0; j--) { if (projectList.get(i).getId().equals(projectList.get(j).getId())) { projectList.remove(j); i-=1; } } }
2.根据equals方法去重
list
3. HashSet去重
利用set元素不可重复的特性
/// 去重 Set<Project> userSet = new HashSet<>(projectFatherList); projectFatherList = new ArrayList<>(userSet);
4. stream流去重
普通版
projectList=projectList.stream().distinct().collect(Collectors.toList());
根据某个字段去重
// 第一种 projectList = projectList.stream().filter(distinctByKey((p) -> (p.getT_custId()))).collect(Collectors.toList()); public static <T>Predicate<T> distinctByKey(Function<? super T, Object> keyExtractor){ Map<Object,Boolean> seen = new ConcurrentHashMap<>(); return t -> seen.putIfAbsent(keyExtractor.apply(t),Boolean.TRUE) == null; }
// 第二种 collectingAndThen List<ExportTemperatureDto> result = temperatureList.stream() .collect( collectingAndThen( toCollection( () -> new TreeSet<>(comparing(ExportTemperatureDto::getPersonId)) ), ArrayList::new ) );
根据某个字段去重也可以重写实体的equals方法
根据多个字段去重
List<ResourcesData> distinctClass = resourcesDataList.stream().collect(Collectors.collectingAndThen(Collectors.toCollection(() -> new TreeSet<>(Comparator.comparing(o -> o.getSkill() + ";" + o.getTechLevel()))), ArrayList::new));
总结
总体上stream流去重是比较方便的,速度上也是比较快