java数组去重总结

方法一:
先遍历原数组,然后遍历结束集,通过每个数组的元素和结果集中的元素进行比对,若相同则break。若不相同,则存入结果集。
两层循环进行遍历得出最终结果。

String[] array = {"a","b","c","c","d","e","e","e","a"};  
List<String> result = new ArrayList<String>();  
boolean flag;  
for(int i=0;i<array.length;i++){  
    flag = false;  
    for(int j=0;jif(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));  
输出结果:[a, b, c, d, e]

方法二
通过使用indexOf方法进行判断结果集中是否存在了数组元素。

String[] array = {"a","b","c","c","d","e","e","e","a"};  
List 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));  

输出结果:[a, b, c, d, e]

方法三
嵌套循环,进行比较获取满足条件结果集。

String[] array = {"a","b","c","c","d","e","e","e","a"};  
List<String> list = new ArrayList<String>();  
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));  

输出结果:[b, c, d, e, a]

方法四
先使用java提供的数组排序方法进行排序,然后进行一层for循环,进行相邻数据的比较即可获得最终结果集。

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 < 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));

输出结果:[a, b, c, d, e]

方法五
加入set方法进行添加,虽然是无序排列,但是也更方便的解决了去重的问题。

String[] array = {"a","b","c","c","d","e","e","e","a"};  
            Set<String> set = new HashSet<String>();  
            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));  

输出结果:[d, e, b, c, a]


总结
①.ArrayList集合转数组

String[] arrayResult = (String[]) list.toArray(new String[list.size()]);  

版权说明:感谢原作者的辛苦创作,如转载涉及版权等问题,我们将在第一时间删除,谢谢。
联系邮箱:[email protected]

你可能感兴趣的:(java数组去重)