目錄
1、使用LinkedHashSet删除ArrayList中的重複資料
2、使用JAVA8新特性stream進行List去重
3、利用HashSet不能添加重複資料的特性
4、利用List的contains方法
5、利用雙重for循環去重
1、使用LinkedHashSet删除ArrayList中的重複資料
/**
* 1.使用LinkedHashSet删除ArrayList中的重複資料
*/
public static void fun1() {
// 初始化資料
List<Integer> list = new ArrayList<>(Arrays.asList(1, 1, 2, 3, 3, 3, 4, 5, 6, 6, 6, 7, 8));
HashSet<Integer> hashSet = new LinkedHashSet<Integer>(list);
// 輸出結果
ArrayList<Integer> result = new ArrayList<>(hashSet);
System.out.println(result);
}
輸出結果:
[1, 2, 3, 4, 5, 6, 7, 8]
2、使用JAVA8新特性stream進行List去重
/**
* 2.使用JAVA8新特性stream進行List去重
*/
public static void fun2() {
// 初始化資料
List<Integer> list = new ArrayList<>(Arrays.asList(1, 1, 2, 3, 3, 3, 4, 5, 6, 6, 6, 7, 8));
// 輸出結果
List<Integer> result = list.stream().distinct().collect(Collectors.toList());
System.out.println(result);
}
輸出結果:
[1, 2, 3, 4, 5, 6, 7, 8]
3、利用HashSet不能添加重複資料的特性
/**
* 3.利用HashSet不能添加重複資料的特性
*/
public static void fun3() {
// 初始化資料
List<Integer> list = new ArrayList<>(Arrays.asList(1, 1, 2, 3, 3, 3, 4, 5, 6, 6, 6, 7, 8));
HashSet<Integer> set = new HashSet<Integer>(list.size());
// 輸出結果
List<Integer> result = new ArrayList<Integer>(list.size());
for (Integer str : list) {
if (set.add(str)) {
result.add(str);
}
}
list.clear();
list.addAll(result);
System.out.println(result);
}
[1, 2, 3, 4, 5, 6, 7, 8]
4、利用List的contains方法
/**
* 4.利用List的contains方法
*/
public static void fun4() {
// 初始化資料
List<Integer> list = new ArrayList<>(Arrays.asList(1, 1, 2, 3, 3, 3, 4, 5, 6, 6, 6, 7, 8));
// 輸出結果
List<Integer> result = new ArrayList<>(list.size());
for (Integer str : list) {
if (!result.contains(str)) {
result.add(str);
}
}
list.clear();
list.addAll(result);
System.out.println(result);
}
[1, 2, 3, 4, 5, 6, 7, 8]
5、利用雙重for循環去重
/**
* 5.利用雙重for循環去重
*/
public static void fun5() {
// 初始化資料
List<Integer> list = new ArrayList<>(Arrays.asList(1, 1, 2, 3, 3, 3, 4, 5, 6, 6, 6, 7, 8));
for (int i = 0; i < list.size(); i++) {
for (int j = i + 1; j < list.size(); j++) {
if (list.get(i) == list.get(j)) {
list.remove(j);
j--;
}
}
}
// 輸出結果
System.out.println(list);
}