方法一 循环元素删除
[c-sharp] view
plaincopy
plaincopy
- public static void removeDuplicate(List list) {
- for ( int i = 0 ; i < list.size() - 1 ; i ++ ) {
- for ( int j = list.size() - 1 ; j > i; j -- ) {
- if (list.get(j).equals(list.get(i))) {
- list.remove(j);
- }
- }
- }
- System.out.println(list);
方法二 // 删除ArrayList中反复元素
[c-sharp] view
plaincopy
plaincopy
- public static void removeDuplicate(List list) {
- for ( int i = 0 ; i < list.size() - 1 ; i ++ ) {
- for ( int j = list.size() - 1 ; j > i; j -- ) {
- if (list.get(j).equals(list.get(i))) {
- list.remove(j);
- }
- }
- }
- System.out.println(list);
方法三 删除ArrayList中反复元素,保持顺序
[c-sharp] view
plaincopy
plaincopy
- // 删除ArrayList中反复元素,保持顺序
- public static void removeDuplicateWithOrder(List list) {
- Set set = new HashSet();
- List newList = new ArrayList();
- for (Iterator iter = list.iterator(); iter.hasNext();) {
- Object element = iter.next();
- if (set.add(element))
- newList.add(element);
- }
- list.clear();
- list.addAll(newList);
- System.out.println( " remove duplicate " + list);
- }
方法四 linq
[c-sharp] view
plaincopy
plaincopy
- IList<string> U_list= new List<string>();
- IList<string> Update_list= new List<string>();
- var ulist = (from li in U_list
- select li).Distinct();
- foreach (var d in ulist)
- {
- Update_list.Add(d);
- }
其它情况:
去除List列表中反复值(3种解决方法)
public static void main(String[] args) {
String[] ar = { "dd", "c", "dd", "ff", "b", "e", "e" };
ArrayList list = new ArrayList();
for (int i = 0; i < ar.length; i++) {
list.add(ar[i]);
}
System.out.println("执行前:");
for (int i = 0; i < list.size(); i++) {
System.out.print(list.get(i) + " ");
}
System.out.println();
/* 第一种方法 */
/**
* set方法去除list中反复的数据 set中插入反复的值仅仅保留一个
*/
HashSet h = new HashSet(list);
list.clear();
list.addAll(h);
/* 第一种方法 */ /* 另外一种方法 */
/**
* 第二中方法去除list中反复的数据
*/
Set set = new HashSet();
List newList = new ArrayList();
for (Iterator iter = list.iterator(); iter.hasNext();) {
Object element = iter.next();
if (set.add(element))
newList.add(element);
}
list.clear();
list.addAll(newList);
/* 另外一种方法 */ /* 第三种方法 */
/**
* 普通的方法去除list中反复的数据
*/
for (int i = 0; i < list.size() - 1; i++) {
for (int j = list.size() - 1; j > i; j--) {
if (list.get(j).equals(list.get(i))) {
list.remove(j);
}
}
}
/* 第三种方法 */
System.out.println("执行后:");
for (int i = 0; i < list.size(); i++) {
System.out.print(list.get(i) + " ");
}
}