当前位置:网站首页>stream去重相同属性对象
stream去重相同属性对象
2022-08-09 14:53:00 【Java升级之路】
近日遇到一个list集合,里面有重复的对象,需要去重,因为遇到的比较少,特此记录一下处理方式:
@Test
public void streamTest8() {
List<Person> personList = new ArrayList<Person>();
personList.add(new Person("鸣人", 8900, 18, "1", "螺旋丸"));
personList.add(new Person("鸣人", 8900, 18, "1", "螺旋丸"));
personList.add(new Person("小樱", 7800, 17, "2", "治疗术"));
personList.add(new Person("小樱", 7800, 17, "2", "治疗术"));
personList.add(new Person("大蛇丸", 9500, 31, "1", "八岐大蛇"));
personList.add(new Person("佐助", 8900, 18, "2", "须佐能乎"));
personList.add(new Person("纲手", 7900, 29, "2", "百豪之术"));
// list 一个条件 去重
List<Person> uniqueByName = personList.stream().collect(
Collectors.collectingAndThen(
Collectors.toCollection(() -> new TreeSet<>(Comparator.comparing(Person::getName))), ArrayList::new));
System.out.println("一个条件去重后的list:" + uniqueByName);
// list 多个条件 去重
List<Person> uniqueBySalaryAndAge = personList.stream().collect(
Collectors.collectingAndThen(
Collectors.toCollection(() -> new TreeSet<>(
Comparator.comparing(p -> p.getSalary() + ";" + p.getAge()))), ArrayList::new));
System.out.println("多个条件去重后的list:" + uniqueBySalaryAndAge);
}运行结果:

边栏推荐
猜你喜欢
随机推荐
LNK1123:转换到COFF期间失败:文件无效或损坏
C语言运算符优先级
For programming trading, focusing on forecast or on countermeasures?
Mathematica 作图详解
[MySql]实现多表查询-一对一,一对多
多线程学习
贝塞尔函数
How to flexibly use the advantages of the quantitative trading interface to complement each other?
二叉排序树的左旋与右旋
九、【Vue-Router】缓存路由组件 keep-alive标签
[ERR] 1273 - Unknown collation: ‘utf8mb4_0900_ai_ci‘
名词概念总结(不定期更新~~)
What are the hot topics in quantitative programmatic trading?
How can I know if quantitative programmatic trading is effective?
Suddenly want to analyze the mortgage interest rate and interest calculation
Analysis: Which method is used to build a stock quantitative trading database?
【小白必看】初始C语言(下)
Servlet life cycle
The difference between show and exec in Qt dialog
JVM简学笔记








