Java通过Stream对象集合去重方式

@Data
@RequiredArgsConstructor
@AllArgsConstructor
public class User {
    
    private int id;
    
    private String name;
    
    private String password;
    
    private long classId;
}

默认去重(不起作用)

  public static void main(String[] args) {
        List<User> list = Arrays.asList(new User(3, "a", "a1", 2), new User(2, "b", "b1", 2), new User(1, "c", "c1", 3), new User(2, "b", "b1", 1),
                new User(2, "c", "c2", 4));
        method1(list);
    }
    
    //默认去重(不起作用)
    public static void method1(List<User> list) {
    
        list.stream().distinct().forEach(System.out::println);
    }

 单属性去重

   //指定单属性去重
    public static void method2(List<User> list) {
       list.stream()
                .collect(Collectors.toMap(
                        User::getName, // Key is the name property
                        item -> item, // Value is the person object itself
                        (existing, replacement) -> existing // In case of duplicate keys, keep the existing value
                ))
                .values()
                .stream()
                .toList().forEach(System.out::println);;
        
    }

双属性去重(名称+密码)

 list.stream()
                .collect(Collectors.toMap(
                        item->item.getName()+item.getPassword(), // Key is the name property
                        item -> item, // Value is the person object itself
                        (existing, replacement) -> existing // In case of duplicate keys, keep the existing value
                ))
                .values()
                .stream()
                .toList().forEach(System.out::println);

以此类推,如果是三个属性去重,只需要把key变为三个属性的拼接字符。

自定义去重方法

   public 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;
    }
 list.stream().filter(User.distinctByKey(user -> user.getName()+user.getPassword()))
                .forEach(System.out::println);

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值