当前位置:网站首页>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 !
边栏推荐
- Swift saves an array of class objects with userdefaults and nssecurecoding
- 卷起來,突破35歲焦慮,動畫演示CPU記錄函數調用過程
- StaticLayout的使用详解
- Personal website construction tutorial | local website environment construction | website production tutorial
- 宝塔面板MySQL无法启动
- 单片机原理与接口技术(ESP8266/ESP32)机器人类草稿
- Cerebral cortex: directed brain connection recognition widespread functional network abnormalities in Parkinson's disease
- Node-RED系列(二九):使用slider与chart节点来实现双折线时间序列图
- Wechat applet - simple diet recommendation (4)
- Android SQLite database encryption
猜你喜欢
如何判断线程池已经执行完所有任务了?
Generics, generic defects and application scenarios that 90% of people don't understand
程序员如何活成自己喜欢的模样?
自动化规范检查软件如何发展而来?
Node red series (29): use slider and chart nodes to realize double broken line time series diagram
Swift set pickerview to white on black background
Unity particle special effects series - the poison spray preform is ready, and the unitypackage package can be used directly - next
伪类元素--before和after
钉钉、企微、飞书学会赚钱了吗?
A high density 256 channel electrode cap for dry EEG
随机推荐
字节跳动面试官:一张图片占据的内存大小是如何计算
Unity粒子特效系列-毒液喷射预制体做好了,unitypackage包直接用 -下
面试:Bitmap像素内存分配在堆内存还是在native中
Swift uses userdefaults and codable to save an array of class objects or structure instances
uniapp + uniCloud+unipay 实现微信小程序支付功能
@JsonAdapter注解使用
NCP1342芯片替代料PN8213 65W氮化镓充电器方案
Fluent generates icon prompt logo widget
ThreadLocal source code learning
Apache DolphinScheduler 入门(一篇就够了)
Wechat applet - simple diet recommendation (3)
【小技巧】获取matlab中cdfplot函数的x轴,y轴的数值
How Windows bat script automatically executes sqlcipher command
[NTIRE 2022]Residual Local Feature Network for Efficient Super-Resolution
.Net之延迟队列
leetcode:1200. 最小绝对差
Z-blog template installation and use tutorial
ConstraintLayout官方提供圆角ImageFilterView
The king of pirated Dall · e? 50000 images per day, crowded hugging face server, and openai ordered to change its name
Using directive in angualr2 to realize that the picture size changes with the window size