正如我们所知,ArrayList允许添加重复的元素。在这篇文章中,我们写一个程序,用不同的方法从ArrayList中删除重复的元素。
我们可以用三种方法编写逻辑,从ArrayList中删除重复的元素。
我们知道,HashSet类只包含唯一的值,不允许重复的值加入其中。我们只需将ArrayList转换为HashSet。
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashSet;
import java.util.List;
public class RemoveDuplicatesFromArrayList {
public static void main(final String[] args) {
final List<Integer> listWithDuplicates = new ArrayList<>();
listWithDuplicates.add(10);
listWithDuplicates.add(20);
listWithDuplicates.add(30);
listWithDuplicates.add(30);
listWithDuplicates.add(50);
listWithDuplicates.add(50);
listWithDuplicates.add(10);
System.out.println("Before removing duplicates ::
" + Arrays.toString(listWithDuplicates.toArray()));
final List<Integer> listWithoutDuplicates = new ArrayList<>(
new HashSet<>(listWithDuplicates));
System.out.println("After removing duplicates :: "
+ Arrays.toString(listWithoutDuplicates.toArray()));
}
}
输出:
Before removing duplicates :: [10, 20, 30, 30, 50, 50, 10]
After removing duplicates :: [50, 20, 10, 30]
public class RemoveDuplicatesFromArrayList {
public static void main(final String[] args) {
final List<Integer> listWithDuplicates = new ArrayList<>();
listWithDuplicates.add(10);
listWithDuplicates.add(20);
listWithDuplicates.add(30);
listWithDuplicates.add(30);
listWithDuplicates.add(50);
listWithDuplicates.add(50);
listWithDuplicates.add(10);
System.out.println("Before removing duplicates :: "
+ Arrays.toString(listWithDuplicates.toArray()));
final List<Integer> listWithoutDuplicates = listWithDuplicates.stream()
.distinct()
.collect(Collectors.toList());
System.out.println("After removing duplicates :: "
+ Arrays.toString(listWithoutDuplicates.toArray()));
}
}
输出:
Before removing duplicates :: [10, 20, 30, 30, 50, 50, 10]
After removing duplicates :: [10, 20, 30, 50]
Before removing duplicates :: [10, 20, 30, 30, 50, 50, 10]
After removing duplicates :: [10, 20, 30, 50]
import java.util.ArrayList;
import java.util.Arrays;
import java.util.LinkedHashSet;
import java.util.List;
public class RemoveDuplicatesFromArrayList {
public static void main(final String[] args) {
final List<Integer> listWithDuplicates = new ArrayList<>();
listWithDuplicates.add(10);
listWithDuplicates.add(20);
listWithDuplicates.add(30);
listWithDuplicates.add(30);
listWithDuplicates.add(50);
listWithDuplicates.add(50);
listWithDuplicates.add(10);
System.out.println("Before removing duplicates :: "
+ Arrays.toString(listWithDuplicates.toArray()));
final List<Integer> listWithoutDuplicates = new ArrayList<>(
new LinkedHashSet<>(listWithDuplicates));
System.out.println("After removing duplicates :: "
+ Arrays.toString(listWithoutDuplicates.toArray()));
}
}
输出
Before removing duplicates :: [10, 20, 30, 30, 50, 50, 10]
After removing duplicates :: [10, 20, 30, 50]
版权说明 : 本文为转载文章, 版权归原作者所有 版权申明
原文链接 : https://www.javaguides.net/2018/08/how-to-remove-duplicate-elements-from-arraylist-in-java.html
内容来源于网络,如有侵权,请联系作者删除!