循环去重
方法一:循环元素删除 // 删除ArrayList中重复元素public static void removeDuplicate(List list) {
for ( int i = 0 ; i < () - 1 ; i ++ ) {
for ( int j = () - 1 ; j > i; j -- ) {
if ((j).equals((i))) {
(j);
}
}
}
(list);
}
方法二:通过HashSet剔除
// 删除ArrayList中重复元素
public static void removeDuplicate(List list) {
HashSet h = new HashSet(list);
();
(h);
(list);
}
方法三: 删除ArrayList中重复元素,保持顺序
// 删除ArrayList中重复元素,保持顺序
public static void removeDuplicateWithOrder(List list) {
Set set = new HashSet();
List newList = new ArrayList();
for (Iterator iter = (); ();) {
Object element = ();
if ((element))
(element);
}
();
(newList);
( " remove duplicate " + list);
}
方法四:
publi List<String> getNewList(List<String> li){
List<String> list = new ArrayList<String>();
for(int i=0; i<(); i++){
String str = (i); //获取传入集合对象的每一个元素
if(!(str)){ //查看新集合中是否有指定的元素,如果没有则加入
(str);
}
}
return list; //返回集合
}
public class Test{
public static void main(String[] args){
ArrayList<String> arr = new ArrayList<String>();
("aaa");
("bbb");
("aaa");
("ccc");
arr = getNewList(arr); //方法去重
(arr);
}
}
方法五:
ArrayList<String> result = new ArrayList<String>();
for(String s: sources){
if((reslut, s) < 1) (s);
}
hashtable去重
核心想法是利用hashtable不可以存在相同键的特性,将list里的每一条数据分循环入hashtable里的 key,value,遇到相同的数据即可跳过,循环完毕后去重的数据全部存放在hashtable内,如果需要将去重的数据放入list,可以new一个新的list,将去重的数据放入新的list中List<string> yuanList=new List<string>();
List<string> copyList=new List<copyList>();
Hashtable hash=new Hashtable();
foreach (string str in yuanList)//源LIST去重
{
if (!(str))
{
(str, str);
(str);//把不重复的列加入
}
}