当前位置:网站首页>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 !
边栏推荐
- How to get the STW (pause) time of GC (garbage collector)?
- Glide advanced level
- 【小技巧】獲取matlab中cdfplot函數的x軸,y軸的數值
- Matrix processing practice
- ThreadLocal source code learning
- To bring Euler's innovation to the world, SUSE should be the guide
- Tianlong Babu TLBB series - questions about skill cooling and the number of attack ranges
- How to use sqlcipher tool to decrypt encrypted database under Windows system
- 《微信小程序-基础篇》小程序中的事件与冒泡
- 一种用于干式脑电图的高密度256通道电极帽
猜你喜欢

The comparison of every() and some() in JS uses a power storage plan

How Windows bat script automatically executes sqlcipher command

QT realizes signal transmission and reception between two windows

剪掉ImageNet 20%数据量,模型性能不下降!Meta斯坦福等提出新方法,用知识蒸馏给数据集瘦身...

程序员如何活成自己喜欢的模样?

《微信小程序-基础篇》小程序中的事件与冒泡

.Net之延迟队列

ArcGIS Pro creating features

Design of stepping motor controller based on single chip microcomputer (forward rotation and reverse rotation indicator gear)

RMS TO EAP通过MQTT简单实现
随机推荐
isEmpty 和 isBlank 的用法区别
【小技巧】获取matlab中cdfplot函数的x轴,y轴的数值
天龙八部TLBB系列 - 关于包裹掉落的物品
善用兵者,藏于无形,90 分钟深度讲解最佳推广价值作品
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
如何判断线程池已经执行完所有任务了?
Uncover the practice of Baidu intelligent testing in the field of automatic test execution
Small program startup performance optimization practice
@SerializedName注解使用
盗版DALL·E成梗图之王?日产5万张图像,挤爆抱抱脸服务器,OpenAI勒令改名
StaticLayout的使用详解
ArcGIS Pro creating features
一种用于干式脑电图的高密度256通道电极帽
程序员如何活成自己喜欢的模样?
uniapp + uniCloud+unipay 实现微信小程序支付功能
让AI替企业做复杂决策真的靠谱吗?参与直播,斯坦福博士来分享他的选择|量子位·视点...
Node-RED系列(二九):使用slider与chart节点来实现双折线时间序列图
RMS TO EAP通过MQTT简单实现
Lepton 无损压缩原理及性能分析
Unity particle special effects series - the poison spray preform is ready, and the unitypackage package can be used directly - next