java 对象数组 对象相同元素去重

本文介绍了如何在Java 8中利用Stream API结合自定义鉴别器实现对象数组去重。通过创建一个distinctByKey()方法,可以基于对象的特定属性进行过滤,有效去除数组中相同对象的冗余。

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

public class Book {

   private String name;
   private int price;

   
   public Book(String name, int price) {
       this.name = name;
       this.price = price;
   }
   public String getName() {
       return name;
   }
   public int getPrice() {
       return price;
   }

   public void setName(String name) {
       this.name = name;
   }

   public void setPrice(int price) {
       this.price = price;
   }
}
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;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;

@SpringBootApplication
public class ObjectDeWeightApplication {

    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()));
        
        SpringApplication.run(ObjectDeWeightApplication.class, args);
    }

    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;
    }

}

在这里插入图片描述

 List<Integer> listWithoutDuplicates = numbersList.stream().distinct().collect(Collectors.toList());
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值