摘自文章:# List 去重的 6 种方法,这个方法最完美!
talk is cheap, show you the code:
package com.cc;
import java.util.*;
import java.util.stream.Collectors;
public class Main {
public static void main(String[] args) {
// list作为原始数据不可变
List<Integer> list = Arrays.asList(1,1,2,2,3,3,4,4,5,5,6,6,7,7,8,8,9,9);
System.out.println("original: " + list);
/**
* contains判断去重,有序
*/
{
List<Integer> newList = new ArrayList<>();
for (Integer value : list) {
if (!newList.contains(value)) {
newList.add(value);
}
}
System.out.println("newList by contains: " + newList);
}
/**
* 迭代器去重,无序
* 得到的新集合排序顺序和集合不一致
*/
{
List<Integer> newList = new ArrayList<>(list);
Iterator<Integer> iterator = newList.iterator();
while (iterator.hasNext()) {
Integer value = iterator.next();
// 存在两个相同的值
if (newList.indexOf(value) != newList.lastIndexOf(value)) {
iterator.remove();
}
}
System.out.println("newList by iterator: " + newList);
}
/**
* hash去重,无序
* HashSet会自动排序
*/
{
HashSet<Integer> hashSet = new HashSet<>(list);
System.out.println("newList by HashSet: " + hashSet);
}
/**
* LinkedHashSet去重,有序
* 该方式的使用简单方便,生成的新集合与原数组顺序一致,可以采用
*/
{
LinkedHashSet<Integer> linkedHashSet = new LinkedHashSet<>(list);
System.out.println("newList by LinkedHashSet: " + linkedHashSet);
}
/**
* TreeSet去重,无序
*/
{
TreeSet<Integer> treeSet = new TreeSet<>(list);
System.out.println("newList by TreeSet: " + treeSet);
}
/**
* Stream去重,有序
* 不用创建新对象,使用自身去接收去重的结果,该方式最佳
*/
{
List<Integer> newList = new ArrayList<>(list);
newList = newList.stream().distinct().collect(Collectors.toList());
System.out.println("newList by Stream: " + newList);
}
}
}