1、使用LinkedHashSet删除arraylist中的重复数据
LinkedHashSet是在一个ArrayList删除重复数据的最佳方法。LinkedHashSet在内部完成两件事:
public static void main(String[] args) { int List[] =[1, 1, 2, 3, 3, 3, 4, 5, 6, 6, 6, 7, 8]
//带参构造器,参数为 集合
LinkedHashSet<Integer> hashSet = new LinkedHashSet<>(List)
//带参构造器(集合) ArrayList<Integer> listWithoutDuplicates = new ArrayList<>(hashSet); System.out.println(listWithoutDuplicates); }
public static void main(String[] args){ int List[] =[1, 1, 2, 3, 3, 3, 4, 5, 6, 6, 6, 7, 8]
//distinct() 去除重复数据
//collection(Collectors.toList()) 收集数据
List<Integer> listWithoutDuplicates = List.stream().distinct().collect(Collectors.toList()); System.out.println(listWithoutDuplicates); }
private static void removeDuplicate(List<String> list) {
HashSet<String> set = new HashSet<String>(list.size());
List<String> result = new ArrayList<String>(list.size());
for (String str : list) {
if (set.add(str)) {
result.add(str);
}
}
list.clear();
list.addAll(result);
}
private static void removeDuplicate(List<String> list) {
List<String> result = new ArrayList<String>(list.size());
for (String str : list) {
if (!result.contains(str)) {
result.add(str);
}
}
list.clear();
list.addAll(result);
}
public static void main(String[] args) { int List[] = [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--; } } } }
参考:https://blog.csdn.net/qq_37939251/article/details/90713643
原文:https://www.cnblogs.com/wongzzh/p/15015768.html