当前位置:网站首页>面试:List 如何根据对象的属性去重?
面试:List 如何根据对象的属性去重?
2022-07-05 09:41:00 【沙漠一只雕得儿得儿】
一、去除List中重复的String
public List<String> removeStringListDupli(List<String> stringList) {
Set<String> set = new LinkedHashSet<>();
set.addAll(stringList);
stringList.clear();
stringList.addAll(set);
return stringList;
}
或使用Java8的写法:
List<String> unique = list.stream().distinct().collect(Collectors.toList());
二、List中对象去重
比如现在有一个 Person类:
public class Person {
private Long id;
private String name;
public Person(Long id, String name) {
this.id = id;
this.name = name;
}
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
@Override
public String toString() {
return "Person{" +
"id=" + id +
", name='" + name + '\'' +
'}';
}
}
重写Person对象的equals()方法和hashCode()方法:
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
Person person = (Person) o;
if (!id.equals(person.id)) return false;
return name.equals(person.name);
}
@Override
public int hashCode() {
int result = id.hashCode();
result = 31 * result + name.hashCode();
return result;
}
下面对象去重的代码:
Person p1 = new Person(1l, "jack");
Person p2 = new Person(3l, "jack chou");
Person p3 = new Person(2l, "tom");
Person p4 = new Person(4l, "hanson");
Person p5 = new Person(5l, "胶布虫");
List<Person> persons = Arrays.asList(p1, p2, p3, p4, p5, p5, p1, p2, p2);
List<Person> personList = new ArrayList<>();
// 去重
persons.stream().forEach(
p -> {
if (!personList.contains(p)) {
personList.add(p);
}
}
);
System.out.println(personList);
List 的contains()方法底层实现使用对象的equals方法去比较的,其实重写equals()就好,但重写了equals最好将hashCode也重写了。
我们创建了一个高质量的技术交流群,与优秀的人在一起,自己也会优秀起来,赶紧点击加群,享受一起成长的快乐。
可以参见:
http://stackoverflow.com/questions/30745048/how-to-remove-duplicate-objects-from-java-arraylist
http://blog.csdn.net/growing_tree/article/details/46622579
三、根据对象的属性去重
下面要根据Person对象的id去重,那该怎么做呢?
写一个方法吧:
public static List<Person> removeDupliById(List<Person> persons) {
Set<Person> personSet = new TreeSet<>((o1, o2) -> o1.getId().compareTo(o2.getId()));
personSet.addAll(persons);
return new ArrayList<>(personSet);
}
通过Comparator比较器,比较对象属性,相同就返回0,达到过滤的目的。
再来看比较炫酷的Java8写法:
import static java.util.Comparator.comparingLong;
import static java.util.stream.Collectors.collectingAndThen;
import static java.util.stream.Collectors.toCollection;
// 根据id去重
List<Person> unique = persons.stream().collect(
collectingAndThen(
toCollection(() -> new TreeSet<>(comparingLong(Person::getId))), ArrayList::new)
);
这段炫酷的代码是google的,还不明白是怎么个原理,等我好好研究一下,再专门写篇文章好好阐述一下。
还有一种写法:
public static <T> Predicate<T> distinctByKey(Function<? super T, Object> keyExtractor) {
Map<Object, Boolean> map = new ConcurrentHashMap<>();
return t -> map.putIfAbsent(keyExtractor.apply(t), Boolean.TRUE) == null;
}
// remove duplicate
persons.stream().filter(distinctByKey(p -> p.getId())).forEach(p -> System.out.println(p));
java8 确实简化了很多冗长的操作,精简了代码,小伙,研究java8去吧!
边栏推荐
- Comment obtenir le temps STW du GC (collecteur d'ordures)?
- Tdengine can read and write through dataX, a data synchronization tool
- 【OpenCV 例程200篇】219. 添加数字水印(盲水印)
- Using directive in angualr2 to realize that the picture size changes with the window size
- . Net delay queue
- 让AI替企业做复杂决策真的靠谱吗?参与直播,斯坦福博士来分享他的选择|量子位·视点...
- Apache DolphinScheduler 入门(一篇就够了)
- Apache DolphinScheduler 系统架构设计
- Design of stepping motor controller based on single chip microcomputer (forward rotation and reverse rotation indicator gear)
- Evolution of Baidu intelligent applet patrol scheduling scheme
猜你喜欢

美图炒币半年亏了3个亿,华为被曝在俄罗斯扩招,AlphaGo的同类又刷爆一种棋,今日更多大新闻在此...

Why don't you recommend using products like mongodb to replace time series databases?
![[NTIRE 2022]Residual Local Feature Network for Efficient Super-Resolution](/img/f3/782246100bca3517d95869be80d9c5.png)
[NTIRE 2022]Residual Local Feature Network for Efficient Super-Resolution

Tongweb set gzip

Unity粒子特效系列-毒液喷射预制体做好了,unitypackage包直接用 -下

解决idea调试过程中liquibase – Waiting for changelog lock….导致数据库死锁问题

Viewpager pageradapter notifydatasetchanged invalid problem

Tdengine connector goes online Google Data Studio app store

一种用于干式脑电图的高密度256通道电极帽

How to get the STW (pause) time of GC (garbage collector)?
随机推荐
【小技巧】获取matlab中cdfplot函数的x轴,y轴的数值
【小技巧】獲取matlab中cdfplot函數的x軸,y軸的數值
Theme. AppCompat. Light. Darkactionbar not found
卷起來,突破35歲焦慮,動畫演示CPU記錄函數調用過程
Tianlong Babu TLBB series - single skill group injury
搞数据库是不是越老越吃香?
Advanced opencv:bgr pixel intensity map
Click the picture in the mobile browser and the picture will not pop up
H. 265 introduction to coding principles
Observation cloud and tdengine have reached in-depth cooperation to optimize the cloud experience of enterprises
Uncover the practice of Baidu intelligent testing in the field of automatic test execution
Unity particle special effects series - the poison spray preform is ready, and the unitypackage package is directly used - on
La voie de l'évolution du système intelligent d'inspection et d'ordonnancement des petites procédures de Baidu
Is it really reliable for AI to make complex decisions for enterprises? Participate in the live broadcast, Dr. Stanford to share his choice | qubit · viewpoint
. Net delay queue
oracle和mysql批量Merge对比
Using directive in angualr2 to realize that the picture size changes with the window size
[C language] the use of dynamic memory development "malloc"
Android SQLite database encryption
程序员如何活成自己喜欢的模样?