Five methods of de duplication in Java list
preface
Weight removal is essential for many occasions. I wrote this article because in a previous picture, I performed distinct and order by de duplication in the database and found that it affected the efficiency, so I did de duplication in the background first; Therefore, this article has been recorded for reference:
Num1: List de duplication using stream, a new feature of java8
public static void main(String[] args) {
List list = new ArrayList();
list.add(10);
list.add(11);
list.add(14);
list.add(10);
list.add(19);
list.add(12);
System.out.println("初始化集合为:"+list);
List newList = (List) list.stream().distinct().collect(Collectors.toList());
System.out.println("java8新特性stream去重后集合为:"+newList);
}
The result is:
Num2: double for loop de duplication
public static void main(String[] args) {
List list = new ArrayList();
list.add(10);
list.add(11);
list.add(14);
list.add(10);
list.add(19);
list.add(12);
System.out.println("初始化集合为:"+list);
for (int i = 0; i < list.size(); i++) {
for (int j = 0; j < list.size(); j++) {
if(i!=j&&list.get(i)==list.get(j)) {
list.remove(list.get(j));
}
}
}
System.out.println("去重过后新集合为:"+list);
}
The result is:
Num3: set the judgment to remove the duplicate without disturbing the order
public static void main(String[] args) {
List list = new ArrayList();
list.add(10);
list.add(11);
list.add(14);
list.add(10);
list.add(19);
list.add(12);
System.out.println("初始化集合为:"+list);
Set set1 = new HashSet();
List newList = new ArrayList();
for (Object integer : list) {
if(set1.add(integer)) {
newList.add(integer);
}
}
System.out.println("set集合判断去重:"+newList);
}
The result is:
Num4: assign to another list set after traversal
public static void main(String[] args) {
List list = new ArrayList();
list.add(10);
list.add(11);
list.add(14);
list.add(10);
list.add(19);
list.add(12);
System.out.println("初始化集合为:"+list);
List newList2 = new ArrayList();
for (Object integer : list) {
if(!newList2.contains(integer)){
newList2.add(integer);
}
}
System.out.println("去重后新集合为:"+newList2);
}
The result is:
Num5: set and list conversion de duplication
public static void main(String[] args) {
List list = new ArrayList();
list.add(10);
list.add(11);
list.add(14);
list.add(10);
list.add(19);
list.add(12);
System.out.println("初始化集合为:"+list);
Set set2 = new HashSet();
List newList3 = new ArrayList();
set2.addAll(list);
newList3.addAll(set2);
System.out.println("set和list转换去重:"+newList3);
}
The result is:
The above is the whole content of this article. I hope it will help you in your study, and I hope you will support us a lot.
