Java实现删除List集合中的重复元素的方法有很多种,本文只介绍几种常用的方法。简单起见,本例中List的泛型皆为String类型,如果泛型为类,去重方法类似。
1、使用HashSet的无重复的特性,只是去重后的List不能保持原来的顺序
public static void main(String[] args) throws Exception
{
// 原List集合
String[] array = { "aa", "bb", "aa", "cc", "dd", "bb", "ee" };
List list = Arrays.asList(array);
// 使用HashSet去掉重复
Set set = new HashSet(list);
// 得到去重后的新集合
List newList = new ArrayList(set);
System.out.println(newList);
}
运行结果:[dd, ee, aa, bb, cc]
2、循环List集合,将新集合中没有的元素添加至新集合,此法可在去重的同时保持原来的顺序
public static void main(String[] args)
{
//原List集合
String[] array = { "aa", "bb", "aa", "cc", "dd", "bb", "ee" };
List list = Arrays.asList(array);
//使用迭代器删除重复元素,可保持原来的顺序
Iterator iterator = list.iterator();
List newList = new ArrayList();
while (iterator.hasNext())
{
String next = iterator.next();
//将新集合中没有的元素添加到新集合
if (!newList.contains(next))
{
newList.add(next);
}
}
System.out.println(newList);
}
运行结果:[aa, bb, cc, dd, ee]