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 result = new ArrayList<>();  
boolean flag;  
for(int i=0; i
  • 方法二 indexOf()去重
//用indexOf()方法判单结果集list2是否存在当前元素
String[] array = {"a","b","c","c","d","e","e","e","a"};
List list2 = new ArrayList<>();
list2.add(array[0]);
for(int i=1; i
  • 方法三 嵌套循环去重
String[] array = {"a","b","c","c","d","e","e","e","a"};  
List list3 = new ArrayList<>();
for(int i=0; i
  • 方法四 sort排序去重
String[] array = {"a","b","c","c","d","e","e","e","a"};  
Arrays.sort(array);  
List list = new ArrayList<>();  
list.add(array[0]);  
for(int i=1;i
  • 方法五 set方法去重
String[] array = {"a","b","c","c","d","e","e","e","a"};  
Set set = new HashSet<>();  
for(int i=0;i
  • 方法六 Iterator遍历,remove方法移除去重
 List list=new ArrayList<>();
 list.add("a"); list.add("b");  list.add("a");  list.add("c");
 list.add("b"); list.add("d");
 
 List listTemp= new ArrayList<>();  
 Iterator 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);

你可能感兴趣的:(Java集合框架--List去重)