java列表对象,多属性去重

demo

public class OTest {
    static Map<Object, Boolean> seen = new ConcurrentHashMap<>(16);
    public static void main(String[] args) {
        List<SysUserRole> userRoleList = new ArrayList<>();
        SysUserRole sysUserRole = new SysUserRole();
        sysUserRole.setUserId("1");
        sysUserRole.setRoleId(2L);
        userRoleList.add(sysUserRole);
        SysUserRole sysUserRole1 = new SysUserRole();
        sysUserRole1.setUserId("1");
        sysUserRole1.setRoleId(2L);
        userRoleList.add(sysUserRole1);
        
        // 函数去重
        List<SysUserRole> a = userRoleList.stream().filter(distinctByKey(k -> k.getUserId() + ";" + k.getRoleId().toString())).collect(Collectors.toList());

        System.out.println(JSON.toJSONString(a));

        // 比较去重
        userRoleList = userRoleList.stream().collect(Collectors.collectingAndThen(Collectors.toCollection(() -> new TreeSet<>(Comparator.comparing(o -> o.getUserId() + ";" + o.getRoleId()))), ArrayList::new));

        System.out.println(JSON.toJSONString(userRoleList));
    }


    public static <T> Predicate<T> distinctByKey(Function<? super T, ?> keyExtractor) {
        return t -> seen.putIfAbsent(keyExtractor.apply(t), Boolean.TRUE) == null;
    }
}
posted @ 2023-08-11 14:09  倔强的老铁  阅读(145)  评论(0编辑  收藏  举报