Java List去重的6种方法
1. List双重循环去重
String[] array = {"a","b","c","c","d","e","e","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));
先遍历原数组,然后遍历结束集,通过每个数组的元素和结果集中的元素进行比对,若相同则break。若不相同,则存入结果集,两层循环进行遍历得出最终结果。
2. 使用indexOf方法进行判断结果集中是否存在了数组元素去重
String[] array = {"a","b","c","c","d","e","e","e","a"}; List<String> list = new ArrayList<>(); list.add(array[0]); for(int i=1;i<array.length;i++){ if(list.toString().indexOf(array[i]) == -1){ list.add(array[i]); } } String[] arrayResult = (String[]) list.toArray(new String[list.size()]); System.out.println(Arrays.toString(arrayResult));
3. 嵌套循环去重
String[] array = {"a","b","c","c","d","e","e","e","a"}; List<String> list = 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; } } list.add(array[i]); } String[] arrayResult = (String[]) list.toArray(new String[list.size()]); System.out.println(Arrays.toString(arrayResult));
4. 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()]);
5. 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));
加入set方法进行添加,虽然是无序排列,但是也更方便的解决了去重的问题。
6. 利用Iterator遍历,remove方法移除去重
public void testList() { List<Integer> list=new ArrayList<Integer>(); list.add(1); list.add(2); list.add(4); list.add(1); list.add(2); list.add(5); list.add(1); List<Integer> listTemp= new ArrayList<Integer>(); Iterator<Integer> it=list.iterator(); while(it.hasNext()){ int a=it.next(); if(listTemp.contains(a)){ it.remove(); } else{ listTemp.add(a); } } for(Integer i:list){ System.out.println(i); } }
利用LinkedHashSet进行转换也可
版权声明:本文为JAVASCHOOL原创文章,未经本站允许不得转载。