商城首页欢迎来到中国正版软件门户

您的位置: 首页 > 文章列表 > 编程开发 > Java8如何通过Stream对list对象某个属性去重

Java8如何通过Stream对list对象某个属性去重

  发布于2026-07-06 阅读(0)

扫一扫,手机访问

前言

在实际开发中,List集合去重是个再常见不过的需求了——数据量一大、来源一杂,重复记录就冒出来了。很多时候需要的不是花哨的算法,而是一套干净、高效、能直接上手用的解决方案。

这里把平时学习和实践中遇到的几种典型场景做了整理,重点围绕Ja va8的Stream流操作和TreeSet的天然去重特性来展开。当然,方法本身只是工具,最终目的是在保证效率的前提下把事情做对,没必要拘泥于某一种固定写法。

正文

数据对象

为了方便验证,先准备一个静态不可变的List,里面放了四条SyncBalance数据,其中有些字段完全重复,有些某个字段重复——正好覆盖多种去重场景。

private static final List list = asList(
        new SyncBalance(BigDecimal.ZERO, "12345678", 0, 1, "GGBond", 32, 0),
        new SyncBalance(BigDecimal.ZERO, "22345678", 0, 1, "GGBond", 32, 0),
        new SyncBalance(BigDecimal.ZERO, "22345678", 1, 1, "GGBond", 32, 0),
        new SyncBalance(BigDecimal.ZERO, "22345678", 1, 1, "GGBond", 32, 0)
);

1. 对象整体去重

最直接的需求:所有属性都一样才算重复,去掉之后只保留一条。Stream自带的distinct()方法恰好就是干这个的——基于equals()和hashCode()去重,前提是对象正确实现了这两个方法。

/**
 * 1. 对所有属性一样的数据进行去重
 */
public static void allColumnDistinct() {
    List allColumnDistinct = list.stream().distinct().collect(Collectors.toList());
}

2. 单个属性去重(只返回属性)

有时候我们不关心整个对象,只需要拿到去重后的某个字段列表,比如所有不重复的手机号。用map先提取属性,再distinct即可。

/**
 * 2. 对单个属性去重,只返回去重的属性
 */
public static void columnDistinct() {
    List columnDistinct = list.stream().map(SyncBalance::getMobile).distinct().collect(Collectors.toList());
}

3. 单个属性去重

如果既要按某个字段去重,又要保留完整对象呢?这时候Stream自带的distinct就无能为力了,需要借助TreeSet或者自定义的Predicate过滤器。下面给出三种常见写法,各有侧重。

/**
 * 3-1. 对单个属性一样的数据进行去重,下面是对`mobile`去重
 * 利用collectingAndThen + TreeSet,排序规则按mobile
 */
public static void oneColumnDistinctMethodOne() {
    List oneColumnDistinctMethodOne = list.stream().collect(Collectors.collectingAndThen(
            Collectors.toCollection(() -> new TreeSet<>(
                    Comparator.comparing(SyncBalance::getMobile))), ArrayList::new));
}
/**
 * 3-2. 对单个属性一样的数据进行去重,下面是对`mobile`去重(通过自定义属性去重方法)
 */
public static void oneColumnDistinctMethodTwo() {
    List oneColumnDistinctMethodTwo = list.stream().filter(distinctByKey(i -> i.getMobile())).collect(Collectors.toList());
}

/**
* list对象单个字段去重(自定义属性)
* @param keyExtractor 去重的对象字段
* @return
* @param 
*/
public static  Predicate distinctByKey(Function keyExtractor) {
    Map seen = new ConcurrentHashMap<>();
    return t -> seen.putIfAbsent(keyExtractor.apply(t), Boolean.TRUE) == null;
}
/**
 * 3-3. 对单个属性一样的数据进行去重,下面是对`mobile`去重
 * 直接用TreeSet逐个添加,简单暴力
 */
public static void oneColumnDistinctMethodThree() {
    TreeSet oneColumnDistinctMethodThree = new TreeSet<>(Comparator.comparing(i -> i.getMobile()));
    list.forEach(a -> oneColumnDistinctMethodThree.add(a));
}

4. 多个属性去重

当去重条件变成多个字段组合时,思路依然是用TreeSet,只需要把Comparator的规则改为多个字段拼接或链式比较。这里用手机号+状态两个字段举例。

/**
 * 4. 多个字段条件去重
 */
public static void twoColumnDistinct() {
    List twoColumnDistinct = list.stream().collect(Collectors.collectingAndThen(
            Collectors.toCollection(() -> new TreeSet<>(
                    Comparator.comparing(p -> p.getMobile() + ";" + p.getStatus()))), ArrayList::new));
}

验证方法

在主方法中依次调用上面定义的去重方法,并在每个方法的前后打印分隔标记,便于观察结果。

/**
 * 验证的main方法
 * @param args
 */
public static void main(String[] args) {
    allColumnDistinct();
    columnDistinct();
    oneColumnDistinctMethodOne();
    oneColumnDistinctMethodTwo();
    oneColumnDistinctMethodThree();
    twoColumnDistinct();
}

运行结果

allColumnDistinct---v

SyncBalance(accountBalance=0, mobile=12345678, status=0, sysId=1, loginAccountName=GGBond, keepOrUpdate=32, id=0)

SyncBalance(accountBalance=0, mobile=22345678, status=0, sysId=1, loginAccountName=GGBond, keepOrUpdate=32, id=0)

SyncBalance(accountBalance=0, mobile=22345678, status=1, sysId=1, loginAccountName=GGBond, keepOrUpdate=32, id=0)

allColumnDistinct---^

columnDistinct---v

12345678

22345678

columnDistinct---^

oneColumnDistinctMethodOne---v

SyncBalance(accountBalance=0, mobile=12345678, status=0, sysId=1, loginAccountName=GGBond, keepOrUpdate=32, id=0)

SyncBalance(accountBalance=0, mobile=22345678, status=0, sysId=1, loginAccountName=GGBond, keepOrUpdate=32, id=0)

oneColumnDistinctMethodOne---^

oneColumnDistinctMethodTwo---v

SyncBalance(accountBalance=0, mobile=12345678, status=0, sysId=1, loginAccountName=GGBond, keepOrUpdate=32, id=0)

SyncBalance(accountBalance=0, mobile=22345678, status=0, sysId=1, loginAccountName=GGBond, keepOrUpdate=32, id=0)

oneColumnDistinctMethodTwo---^

oneColumnDistinctMethodThree---v

SyncBalance(accountBalance=0, mobile=12345678, status=0, sysId=1, loginAccountName=GGBond, keepOrUpdate=32, id=0)

SyncBalance(accountBalance=0, mobile=22345678, status=0, sysId=1, loginAccountName=GGBond, keepOrUpdate=32, id=0)

oneColumnDistinctMethodThree---^

twoColumnDistinct---v

SyncBalance(accountBalance=0, mobile=12345678, status=0, sysId=1, loginAccountName=GGBond, keepOrUpdate=32, id=0)

SyncBalance(accountBalance=0, mobile=22345678, status=0, sysId=1, loginAccountName=GGBond, keepOrUpdate=32, id=0)

SyncBalance(accountBalance=0, mobile=22345678, status=1, sysId=1, loginAccountName=GGBond, keepOrUpdate=32, id=0)

twoColumnDistinct---^​

Ja va8如何通过Stream对list对象某个属性去重

结尾

集合去重的思路远不止Stream和TreeSet这两种,只要能保证效率和正确性,用HashSet、LinkedHashMap甚至数据库去重都行。关键是理解每种场景下“去重”到底意味着什么——是整个对象、某个字段、还是字段组合?搞清楚需求,选对工具,代码自然干净利落。

本文转载于:https://www.jb51.net/program/366915bxl.htm 如有侵犯,请联系zhengruancom@outlook.com删除。
免责声明:正软商城发布此文仅为传递信息,不代表正软商城认同其观点或证实其描述。

热门关注