集合去重的方法
方法一:双重for循环,每一个元素同其他元素做比较,若相同,则remove();
//list去重:类似选择排序
public static List<Integer> removeDuplicationByFor(List<Integer> list){
for(int i=0; i<list.size(); i++){
for(int j=i+1; j<list.size(); j++){
if(list.get(j).equals(list.get(i))){
list.remove(j);
}
}
}
return list;
}
方法二:使用contains方法判断,将待去重集合添加至新集合
//list去重:使用contains方法判断,将待去重集合添加至新集合
public static List<Integer> removeDuplicationByContains(List<Integer> list){
List<Integer> newList = new ArrayList<Integer>();
for (int i=0; i<list.size(); i++){
if(!newList.contains(list.get(i))){
newList.add(list.get(i));
}
}
list.removeAll(list);
list.addAll(newList);
return list;
}
方法三:使用hashset去重
//list去重:使用hashset实现去重
public static List<Integer> removeDuplicationByHashSet(List<Integer> list){
Set<Integer> set = new HashSet<Integer>();
set.addAll(list);
list.clear();
list.addAll(set);
return list;
}
方法四:使用treeSet去重
//list去重:使用threeset去重
public static List<Integer> removeDuplicationByTreeSet(List<Integer> list){
Set<Integer> set = new TreeSet<Integer>(list);
list.clear();
list.addAll(set);
return list;
}