List元素去重複方法集
阿新 • • 發佈:2019-01-04
[javascript] view
plain copy
-
1. 迴圈list中的所有元素然後刪除重複
- publicstatic List 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);
- }
- }
- }
- return list;
- }
2. 通過HashSet踢除重複元素
- publicstatic List removeDuplicate(List list) {
- HashSet h = new HashSet(list);
- list.clear();
- list.addAll(h);
- return list;
- }
3. 刪除ArrayList中重複元素,保持順序
- // 刪除ArrayList中重複元素,保持順序
- publicstaticvoid 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);
- }
4.把list裡的物件遍歷一遍,用list.contain(),如果不存在就放入到另外一個list集合中
- publicstatic List removeDuplicate(List list){
- List listTemp = new ArrayList();
- for(int i=0;i<list.size();i++){
- if(!listTemp.contains(list.get(i))){
- listTemp.add(list.get(i));
- }
- }
- return listTemp;
- }