首先对List去重,常见的对List去重的方式有以下几种:
-
使用
HashSet
。将List中的元素加入到HashSet中,由于HashSet是不包含重复元素的,因此最后得到的HashSet即为去重后的结果。示例代码如下:List<String> list = new ArrayList<>(Arrays.asList("A", "B", "C", "A", "B")); Set<String> set = new HashSet<>(list); List<String> result = new ArrayList<>(set);
-
使用Java 8 Stream API提供的
distinct()
方法。示例代码如下:List<String> list = new ArrayList<>(Arrays.asList("A", "B", "C", "A", "B")); List<String> result = list.stream().distinct().collect(Collectors.toList());
-
使用自定义函数
distinctByKey()
。该方法接受一个keyExtractor
函数来抽取集合元素中的某个属性,然后根据该属性进行去重,示例代码如下:// 自定义函数distinctByKey() public static <T> Predicate<T> distinctByKey(Function<? super T, ?> keyExtractor) { Set<Object> seen = new HashSet<>(); return t -> seen.add(keyExtractor.apply(t)); } // 使用自定义函数去重 List<Apple> appleList = new ArrayList<Apple>(Arrays.asList( new Apple("red", 100), new Apple("green", 200), new Apple("red", 150), new Apple("green", 150)) ); List<Apple> result = appleList.stream().filter(distinctByKey(Apple::getColor)).collect(Collectors.toList());
以上是几种常见的对List去重的方式,使用哪种方式取决于具体的需求和应用场景。
4.如果是是对List对象去重,还有第4种方法:
//定义空map
Map<String,Boolean> visitedKeys=new HashMap<>();
//利用map对cityId过滤
List<AddressRelationDO> uinqueList=list.stream().filter(a -> !visitedKeys.containsKey(a.getCityId()))
.peek(a -> visitedKeys.put(a.getCityId(), true)).collect(Collectors.toList());
5.利用Map的key,value或者TreeSet属性过滤重复元素。
List<QueryExchangeRateApiBO> rates = new ArrayList<>();
rates.add(new QueryExchangeRateApiBO(....))
...
//返回map
Map<String, QueryExchangeRateApiBO> exchangeRateApiBOMap = rates.stream().collect(Collectors.toMap(k -> k.getCurrencyCode() + k.getExchangeCurrencyCode(), part -> part));
//返回List
List<QueryExchangeRateApiBO> distinctExchangeRateApiList = queryExchangeRateApiList.stream().collect(Collectors.collectingAndThen(Collectors.toCollection(() -> new TreeSet<>(Comparator.comparing(o -> o.getCurrencyCode() + ";" + o.getExchangeCurrencyCode()))), ArrayList::new));