当前位置:网站首页>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 !
边栏推荐
猜你喜欢

Coordinate system of view

Hard core, have you ever seen robots play "escape from the secret room"? (code attached)

isEmpty 和 isBlank 的用法区别

卷起來,突破35歲焦慮,動畫演示CPU記錄函數調用過程

ArcGIS Pro 创建要素

如何获取GC(垃圾回收器)的STW(暂停)时间?

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

QT event filter simple case

Roll up, break 35 - year - old Anxiety, animation Demonstration CPU recording Function call Process

盗版DALL·E成梗图之王?日产5万张图像,挤爆抱抱脸服务器,OpenAI勒令改名
随机推荐
mysql80服务不启动
【 conseils 】 obtenir les valeurs des axes X et y de la fonction cdfplot dans MATLAB
TypeError: Cannot read properties of undefined (reading ‘cancelToken‘)
学习笔记6--卫星定位技术(上)
硬核,你见过机器人玩“密室逃脱”吗?(附代码)
ConstraintLayout的流式布局Flow
QT realizes signal transmission and reception between two windows
历史上的今天:第一本电子书问世;磁条卡的发明者出生;掌上电脑先驱诞生...
MySQL数字类型学习笔记
Unity particle special effects series - the poison spray preform is ready, and the unitypackage package can be used directly - next
面试:Bitmap像素内存分配在堆内存还是在native中
[C language] the use of dynamic memory development "malloc"
Using directive in angualr2 to realize that the picture size changes with the window size
Flutter development: a way to solve the problem of blank space on the top of listview
.Net之延迟队列
Mobile heterogeneous computing technology GPU OpenCL programming (Advanced)
Roll up, break 35 - year - old Anxiety, animation Demonstration CPU recording Function call Process
90%的人都不懂的泛型,泛型的缺陷和应用场景
cent7安装Oracle数据库报错
To bring Euler's innovation to the world, SUSE should be the guide