当前位置:网站首页>Interview: how do lists duplicate objects according to their attributes?
Interview: how do lists duplicate objects according to their attributes?
2022-06-28 02:45:00 【An eagle in the desert】
One 、 Remove List Repeated in String
public List<String> removeStringListDupli(List<String> stringList) {
Set<String> set = new LinkedHashSet<>();
set.addAll(stringList);
stringList.clear();
stringList.addAll(set);
return stringList;
}
Or use Java8 Writing :
List<String> unique = list.stream().distinct().collect(Collectors.toList());
Two 、List Medium object de duplication
For example, now there is a Person class :
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 + '\'' +
'}';
}
}
rewrite Person Object's equals() Methods and hashCode() Method :
@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;
}
The following object de duplication code :
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, " Tape worm ");
List<Person> persons = Arrays.asList(p1, p2, p3, p4, p5, p5, p1, p2, p2);
List<Person> personList = new ArrayList<>();
// duplicate removal
persons.stream().forEach(
p -> {
if (!personList.contains(p)) {
personList.add(p);
}
}
);
System.out.println(personList);
List Of contains() Method to implement the object equals Method to compare , Actually rewrite equals() Just fine , But rewrite equals It is best to hashCode Also rewrite the .
We have created a high-quality technical exchange group , With good people , I will be excellent myself , hurriedly Click Add group , Enjoy growing up together .
You can see :
http://stackoverflow.com/questions/30745048/how-to-remove-duplicate-objects-from-java-arraylist
http://blog.csdn.net/growing_tree/article/details/46622579
3、 ... and 、 According to the properties of the object
The following is based on Person Object's id duplicate removal , What should I do ?
Write a method :
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);
}
adopt Comparator The comparator , Compare object properties , The same goes back to 0, To achieve the purpose of filtration .
Let's look at the cool Java8 How to write it :
import static java.util.Comparator.comparingLong;
import static java.util.stream.Collectors.collectingAndThen;
import static java.util.stream.Collectors.toCollection;
// according to id duplicate removal
List<Person> unique = persons.stream().collect(
collectingAndThen(
toCollection(() -> new TreeSet<>(comparingLong(Person::getId))), ArrayList::new)
);
This cool code is google Of , I don't understand how it works , Wait for me to study , Write another article specifically to elaborate .
There's another way to write it :
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 It does simplify a lot of lengthy operations , Streamlined the code , Boy , Research java8 Go for it !
边栏推荐
- High reliability application knowledge map of Architecture -- the path of architecture evolution
- Is it safe for qiniu to open an account? How do I open an account online?
- Starting sequence of Turing machine
- [JS reverse hundreds of examples] I love to solve 2022 Spring Festival problems and receive red envelopes
- Flashtext, a data cleaning tool, has directly increased the efficiency by dozens of times
- Snake C language
- How technicians become experts in technical field
- 【历史上的今天】6 月 18 日:京东诞生;网店平台 Etsy 成立;Facebook 发布 Libra 白皮书
- 11 timers for STM32F103
- Shardingsphere-proxy-5.0.0 establish MySQL read / write separation connection (6)
猜你喜欢

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

Practice of low code DSL in data warehouse

如何开启多语言文本建议?Win11打开多语言文本建议的方法

【方块编码】基于matlab的图像方块编码仿真

Win11无法使用动态壁纸怎么办?Win11用不了动态壁纸的解决方法
![[today in history] June 2: Apple launched swift programming language; China Telecom acquires China Unicom C network; OS X Yosemite release](/img/24/58c4ee72e067f01a4c4aa57a1cf61a.jpg)
[today in history] June 2: Apple launched swift programming language; China Telecom acquires China Unicom C network; OS X Yosemite release

【历史上的今天】6 月 6 日:世界 IPv6 启动纪念日;《俄罗斯方块》发布;小红书成立

Win11新建不了文本文档?Win11右键无法新建文本文档的解决方法

【历史上的今天】6 月 24 日:网易成立;首届消费电子展召开;世界上第一次网络直播
![[today in history] May 31: the father of Amiga was born; The co developer of basic language was born; BlackBerry BBM shutdown](/img/6e/f0e71bb941d5940dbf6d51b812b52e.png)
[today in history] May 31: the father of Amiga was born; The co developer of basic language was born; BlackBerry BBM shutdown
随机推荐
Interpretation of bilstm-crf in NER forward_ algorithm
Redis~Geospatial(地理空间)、Hyperloglog(基数统计)
Exploration on the construction path of real-time digital warehouse integrating digital intelligence learning and streaming batch
面试:Bitmap像素内存分配在堆内存还是在native中
[today in history] June 5: Lovelace and Babbage met; The pioneer of public key cryptography was born; Functional language design pioneer born
【历史上的今天】6 月 18 日:京东诞生;网店平台 Etsy 成立;Facebook 发布 Libra 白皮书
KVM related
Opencv -- Hough transform and some problems encountered
共阳极数码管真值表
Flashtext, a data cleaning tool, has directly increased the efficiency by dozens of times
How to enable multi language text suggestions? Win11 method to open multilingual text suggestions
关于st-link usb communication error的解决方法
How does win11 add printers and scanners? Win11 add printer and scanner settings
MFC common current path
毕业总结
【历史上的今天】6 月 16 日:甲骨文成立;微软 MSX 诞生;快速傅里叶变换发明者出生
stm32f1中断介绍
在线文本按行批量反转工具
【历史上的今天】6 月 3 日:微软推出必应搜索引擎;Larry Roberts 启动阿帕网;Visual Basic 之父出生
【方块编码】基于matlab的图像方块编码仿真