集合对象去重工具

        在业务中,经常会遇到需要根据对象中的某个字段进行去重,以下是比较方便的两个方法:

public class StreamUtil {

    /**
     * 流式去重工具
     *
     * @param function
     * @param <K>
     * @return
     */
    public static  <K> Predicate<K> distinctPredicate(Function<K,Object> function){
        Map<Object, Boolean> map = new ConcurrentHashMap<>();
        return (t)-> null == map.putIfAbsent(function.apply(t),true);

    }

    /**
     * 将集合先放到 treeSet 集合然后将他们转换成数组,根据集合内对象的某个属性去重
     * 将o -> o.hashCode()换成对应的属性即可
     *
     * @param list
     * @return
     */
    public static List<Object> distinctByTreeSet(List<Object> list){
        List<Object> distinctList = list.stream().collect(
                // 将集合先放到 treeSet 集合然后将他们转换成数组
                Collectors.collectingAndThen(
                        Collectors.toCollection(() -> new TreeSet<>(Comparator.comparing(o -> o.hashCode())))
                        , ArrayList::new)
        );
        return distinctList;
    }

    public static void main(String[] args) {
        User user1 = new User(1, "小明");
        User user2 = new User(2, "小明");
        List<User> users = new ArrayList<>();
        users.add(user1);
        users.add(user2);

        List<User> distinctUserList= users.stream().filter(distinctPredicate(m -> m.getName())).collect(Collectors.toList());
        System.out.println(distinctUserList);

    }

    @Data
    @AllArgsConstructor
    @NoArgsConstructor
    static class User{
        private Integer id;
        private String name;

    }


}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值