1,使用 LinkedHashSet 删除 arraylist 中的重复数据
LinkedHashSet 是在一个 ArrayList 删除重复数据的最佳方法,LinkedHashSet 在内部完成两件事
(1).删除重复数据
(2) 保持添加到其中的数据的顺序
import ;
import ;
import ;
public class ArrayListExample
{
public static void main(String[] args)
{
ArrayList<Integer> numbersList = new ArrayList<>((1, 1, 2, 3, 3, 3, 4, 5, 6, 6, 6, 7, 8));
(numbersList);
LinkedHashSet<Integer> hashSet = new LinkedHashSet<>(numbersList);
ArrayList<Integer> listWithoutDuplicates = new ArrayList<>(hashSet);
(listWithoutDuplicates);
}
}
输出结果:
[1, 1, 2, 3, 3, 3, 4, 5, 6, 6, 6, 7, 8]
[1, 2, 3, 4, 5, 6, 7, 8]
2,使用 java8 新特性 stream 进行 List 去重
要从 arraylist 中删除重复项,我们也可以使用 java8 stream api,使用 steam 的 distinct() 方法返回一个由不同数据组成的流,通过对象的 equals() 方法进行比较。
收集所有区域数据 List 使用 ()。
import ;
import ;
import ;
import ;
public class ArrayListExample
{
public static void main(String[] args)
{
ArrayList<Integer> numbersList = new ArrayList<>((1, 1, 2, 3, 3, 3, 4, 5, 6, 6, 6, 7, 8));
(numbersList);
List<Integer> listWithoutDuplicates = ().distinct().collect(());
(listWithoutDuplicates);
}
}
输出结果:
[1, 1, 2, 3, 3, 3, 4, 5, 6, 6, 6, 7, 8]
[1, 2, 3, 4, 5, 6, 7, 8]
3,利用HashSet不能添加重复数据的特性 由于HashSet不能保证添加顺序,所以只能作为判断条件保证顺序
private static void removeDuplicate(List<String> list)
{
HashSet<String> set = new HashSet<String>(());
List<String> result = new ArrayList<String>(());
for (String str : list) {
if ((str)) {
(str);
}
}
();
(result);
}
4,利用List的contains方法循环遍历,重新排序,只添加一次数据,避免重复
private static void removeDuplicate(List<String> list)
{
List<String> result = new ArrayList<String>(());
for (String str : list) {
if (!(str)) {
(str);
}
}
();
(result);
}
5,双重for循环去重
for (int i = 0; i < (); i++) {
for (int j = 0; j < (); j++) {
if(i!=j&&(i)==(j)) {
((j));
}
}
}