Java集合框架--List去重
一、Java List 类
二、Java List 排序
三、Java List 遍历
四、Java List 去重
五、Java List 转Array
四、Java List 去重
- 方法一: 双循环去重
//先遍历原数组array,然后遍历去重过后的result集,通过每个数组的元素和结果集中的元素进行比对
//若相同则break。若不相同,则存入result集。
String[] array = {"a","b","c","c","d","c","e","a"};
List<String> result = new ArrayList<>();
boolean flag;
for(int i=0; i<array.length; ++i){
flag = false;
for(int j=0; j<result.size(); ++j){
if( array[i].equals(result.get(j)) ){
flag = true;
break;
}
}
if(!flag) result.add(array[i]);
}
String[] arrayResult = (String[]) result.toArray(new String[result.size()]);
System.out.println(Arrays.toString(arrayResult));
- 方法二 indexOf()去重
//用indexOf()方法判单结果集list2是否存在当前元素
String[] array = {"a","b","c","c","d","e","e","e","a"};
List<String> list2 = new ArrayList<>();
list2.add(array[0]);
for(int i=1; i<array.length; ++i) {
if ( list2.toString().indexOf( array[i] ) == -1 ) list2.add(array[i]);
}
String[] arrayResult = (String[]) list2.toArray(new String[list2.size()]);
System.out.println(Arrays.toString(arrayResult));
- 方法三 嵌套循环去重
String[] array = {"a","b","c","c","d","e","e","e","a"};
List<String> list3 = new ArrayList<>();
for(int i=0; i<array.length; ++i ) {
for(int j=i+1; j<array.length; ++j) {
if ( array[i] == array[j] ) j = ++i;
}
list3.add(array[i]);
}
String[] arrayResult = (String[]) list3.toArray(new String[list3.size()]);
System.out.println(Arrays.toString(arrayResult));
- 方法四 sort排序去重
String[] array = {"a","b","c","c","d","e","e","e","a"};
Arrays.sort(array);
List<String> list = new ArrayList<>();
list.add(array[0]);
for(int i=1;i<array.length;i++){
if(!array[i].equals(list.get(list.size()-1))){
list.add(array[i]);
}
}
String[] arrayResult = (String[]) list.toArray(new String[list.size()]);
System.out.println(Arrays.toString(arrayResult));
- 方法五 set方法去重
String[] array = {"a","b","c","c","d","e","e","e","a"};
Set<String> set = new HashSet<>();
for(int i=0;i<array.length;i++){
set.add(array[i]);
}
String[] arrayResult = (String[]) set.toArray(new String[set.size()]);
System.out.println(Arrays.toString(arrayResult));
- 方法六 Iterator遍历,remove方法移除去重
List<String> list=new ArrayList<>();
list.add("a"); list.add("b"); list.add("a"); list.add("c");
list.add("b"); list.add("d");
List<String> listTemp= new ArrayList<>();
Iterator<String> it=list.iterator();
while(it.hasNext()){
String a = it.next();
if(listTemp.contains(a)) it.remove();
else listTemp.add(a);
}
for(String i:list) System.out.println(i);