jdk1.8 List 去重

本文介绍Java中如何使用Stream API进行列表元素去重,并演示了基于对象属性进行去重的方法,通过实例展示了如何过滤重复的Book对象。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

元素去重


import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;
public class DistinctSimpleDemo {
    public static void main(String[] args) {
        List<String> list = Arrays.asList("AA", "BB", "CC", "BB", "CC", "AA", "AA");
        long l = list.stream().distinct().count();
        System.out.println("No. of distinct elements:"+l);
        String output = list.stream().distinct().collect(Collectors.joining(","));
        System.out.println(output);
    }
}

输出

No. of distinct elements:3
AA,BB,CC

通过对象中的某个属性进行去重


import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
import java.util.function.Function;
import java.util.function.Predicate;
public class DistinctByProperty {
    public static void main(String[] args) {
        List<Book> list = new ArrayList<>();
        {
        	list.add(new Book("Core Java", 200));
        	list.add(new Book("Core Java", 300));
        	list.add(new Book("Learning Freemarker", 150));
        	list.add(new Book("Spring MVC", 200));
        	list.add(new Book("Hibernate", 300));
        }
        list.stream().filter(distinctByKey(b -> b.getName()))
              .forEach(b -> System.out.println(b.getName()+ "," + b.getPrice()));   
    }
    private static <T> Predicate<T> distinctByKey(Function<? super T, ?> keyExtractor) {
        Map<Object,Boolean> seen = new ConcurrentHashMap<>();
        return t -> seen.putIfAbsent(keyExtractor.apply(t), Boolean.TRUE) == null;
    }
}

输出


Core Java,200
Learning Freemarker,150
Spring MVC,200
Hibernate,300

参考:https://blog.youkuaiyun.com/haiyoung/article/details/80934467

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值