当前位置:网站首页>Interview: how does the list duplicate according to the attributes of the object?
Interview: how does the list duplicate according to the attributes of the object?
2022-07-05 10:12:00 【A bird carved 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 !
边栏推荐
- The comparison of every() and some() in JS uses a power storage plan
- Kotlin compose and native nesting
- leetcode:1200. 最小绝对差
- 天龙八部TLBB系列 - 单体技能群伤
- Apache dolphin scheduler system architecture design
- cent7安装Oracle数据库报错
- Design and Simulation of fuzzy PID control system for liquid level of double tank (matlab/simulink)
- 基于单片机步进电机控制器设计(正转反转指示灯挡位)
- 【系统设计】指标监控和告警系统
- [system design] index monitoring and alarm system
猜你喜欢
To bring Euler's innovation to the world, SUSE should be the guide
Usage differences between isempty and isblank
自动化规范检查软件如何发展而来?
一种用于干式脑电图的高密度256通道电极帽
Meitu lost 300 million yuan in currency speculation for half a year. Huawei was exposed to expand its enrollment in Russia. Alphago's peers have made another breakthrough in chess. Today, more big new
How to correctly evaluate video image quality
基于单片机步进电机控制器设计(正转反转指示灯挡位)
[NTIRE 2022]Residual Local Feature Network for Efficient Super-Resolution
Comment obtenir le temps STW du GC (collecteur d'ordures)?
Wechat applet - simple diet recommendation (4)
随机推荐
C#函数返回多个值方法
《天天数学》连载58:二月二十七日
MySQL digital type learning notes
【C语言】动态内存开辟的使用『malloc』
isEmpty 和 isBlank 的用法区别
Dedecms website building tutorial
Six simple cases of QT
高级 OpenCV:BGR 像素强度图
学习笔记5--高精地图解决方案
Android SQLite database encryption
[system design] index monitoring and alarm system
双容水箱液位模糊PID控制系统设计与仿真(Matlab/Simulink)
【小技巧】获取matlab中cdfplot函数的x轴,y轴的数值
Energy momentum: how to achieve carbon neutralization in the power industry?
[C language] the use of dynamic memory development "malloc"
天龙八部TLBB系列 - 关于包裹掉落的物品
Kotlin compose and native nesting
Flutter development: a way to solve the problem of blank space on the top of listview
Unity粒子特效系列-毒液喷射预制体做好了,unitypackage包直接用 - 上
RMS to EAP is simply implemented through mqtt