当前位置:网站首页>面试:List 如何根据对象的属性去重?
面试:List 如何根据对象的属性去重?
2022-06-28 00:57: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去吧!
边栏推荐
- SQL injection bypass (V)
- 文件傳輸協議--FTP
- JS实现滑动拼图验证
- 【电梯控制系统】基于VHDL语言和状态机实现的电梯控制系统的设计,使用了状态机
- 【历史上的今天】6 月 10 日:Apple II 问世;微软收购 GECAD;发明“软件工程”一词的科技先驱出生
- STM32F103的11个定时器
- Explanation of OSI layer 7 model (easy to understand in Chinese)
- 【倒立摆控制】基于UKF无迹卡尔曼滤波的倒立摆控制simulink仿真
- NER中BiLSTM-CRF解读Forward_algorithm
- SQL报了一个不常见的错误,让新来的实习生懵了
猜你喜欢

STM32F1与STM32CubeIDE编程实例-金属触摸传感器驱动

原理图合并中的技巧

数仓的字符截取三胞胎:substrb、substr、substring

【历史上的今天】6 月 15 日:第一个手机病毒;AI 巨匠司马贺诞生;Chromebook 发布

Starting sequence of Turing machine

数智学习 | 流批一体实时数仓建设路径探索

【云原生】-Docker安装部署分布式数据库 OceanBase

Moving Tencent to the cloud: half of the evolution history of cloud server CVM

【历史上的今天】6 月 13 日:分组交换网路的“亲子纠纷”;博弈论创始人出生;交互式电视初现雏形
![[fuzzy neural network] simulation of fuzzy neural network based on MATLAB](/img/2f/ffe3baf37808b78b2c299aef5a717e.jpg)
[fuzzy neural network] simulation of fuzzy neural network based on MATLAB
随机推荐
启牛开户安全吗?怎么线上开户?
Starting sequence of Turing machine
"Dadao Zhichuang" won a ten million prea+ round of financing and launched a technology consumption robot
Flutter 使用 CustomPaint 绘制基本图形
【历史上的今天】5 月 31 日:Amiga 之父诞生;BASIC 语言的共同开发者出生;黑莓 BBM 停运
JS实现滑动拼图验证
Low code solution - a low code solution for digital after-sales service covering the whole process of work order, maintenance and Finance
MFC CString互转LPVOID
How to realize red, green and yellow traffic lights in ros+gazebo?
Desai wisdom number - histogram (column folding mixed graph): ratio of rental price to rental income in the graduation quarter of 2021
MFC common current path
Anonymous Mount & named mount
Cloud platform KVM migration local virtual machine records
毕业总结
技术人员如何成为技术领域专家
Opencv -- Hough transform and some problems encountered
Solutions to st link USB communication error
Skills in schematic merging
Graduation summary
STM32F103的11个定时器