集合去重的全部方法,总有一款适合你

文章介绍了在Java中对List进行去重的多种方法,包括使用HashSet、Java8的StreamAPI的distinct()函数以及自定义distinctByKey()函数。对于对象属性去重,还展示了利用Map和TreeSet的特性进行处理。选择哪种方法取决于具体需求和场景。
摘要由CSDN通过智能技术生成

首先对List去重,常见的对List去重的方式有以下几种:

  1. 使用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);
    
  2. 使用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());
    
  3. 使用自定义函数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));

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

dmlcq

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值