Java对List对象属性过滤,并去重、压缩操作

244 阅读2分钟

⭐️⭐️ 记录

最近项目中传给前端的对象列表只有几个字段是用来展示的,
而绝大多数的字段是没有参考意义的。
所以,为了使得传参轻量,避免冗余的大量数据,
需要对这个对象列表 List<~>进行去重操作,只展示需要的字段。
(该业务需求比较特殊,大多数情况下不会这么做)
业务描述:

  1. 有对象Class Obj {A, B, C, D, E} ({}里面是属性)
  2. 前端需要对Obj数据进行展示维护,
  3. 表单展示:
Obj A B C D E
o2 1 1 1 2 1
03 1 1 1 2 2
o4 2 3 2 1 2
05 2 3 2 1 3
o6 2 3 2 1 1
o7 2 3 2 3 1

4、其实我只想知道这些数据中ABC三个字段有什么值,与DE无瓜,
5、那就可以将DE忽略,然后对ABC进行去重复。
6、去重复结果

Obj A B C D E
o1 1 1 1 1 2
o4 2 3 2 1 2

7、这样7亿条数据,就变成了2亿条数据。

⭐️⭐️ 方法与代码

⭐️ List<String>去重

说到去重,首先回忆一下普通的List怎么去重,比如List<String>,
这种操作去重的方式有很多,比如:

方法1⃣️

list = list.stream().distinct().collect(Collectors.toList());

方法2⃣️

List<String> listTemp = new ArrayList<String>();  
for(int i=0;i<list.size();i++){  
    if(!listTemp.contains(list.get(i))){  
        listTemp.add(list.get(i));  
    }  
} 

方法3⃣️ 使用HashSet

HashSet set = new HashSet(list);   
list.clear();   
list.addAll(set);   

⭐️ List<Object>单属性去重

举例对象Class Student {id, name, age, class, score, sex}

id name age class score sex
001 胡琪镐 22 2 99
002 徐之陈 22 2 100
002 徐之陈 23 1 95
003 陈迪迪 22 2 99
004 浮华强 25 1 88
005 浮华强 22 2 99
006 浮华强 22 3 99

对于这种对象列表,对但属性的去重操作有以下方法:

方法1⃣️:
去重后对象在集合的顺序变化,
List对象去重,按照对象的某个字段去重,返回去重后新的对象集合

List<Student> newlist =  list
        .stream()
        .collect(Collectors.collectingAndThen(
                Collectors.toCollection(
                () -> new TreeSet<>(
                Comparator.comparing(Student::getName))), ArrayList::new));

方法2⃣️:
去重后对象在集合中顺序跟原集合一样,
List对象去重,按照对象的某个字段去重,返回去重后新的对象集合,
使用方法:用Stream接口的 filter()接收为参数

List<Student> newlist =  list
        .stream()
        .collect(Collectors.collectingAndThen(
                Collectors.toCollection(
                () -> new TreeSet<>(
                Comparator.comparing(Student::getName))), ArrayList::new));

去重结果:

id name age class score sex
001 胡琪镐 22 2 99
002 徐之陈 22 2 100
003 陈迪迪 22 2 99
004 浮华强 25 1 88

⭐️ List<Object>多属性去重

⭐️⭐️ 解读

⭐️⭐️ 备注