2015年9月17日 星期四

[java]移除List中重複的Object

[java]移除List中重複的Object

其中(一)~(三)不限List型態

(一)使用 set

public static <E> List<E> removeDuplicates(List<E> list){
    Set<E> unique = new LinkedHashSet<>(list);
    list.clear();
    list.addAll(unique);
    return list;
}

(二)使用set

public static <E> List<E> removeNonUnique(List<E> list){
    Set<E> seen = new HashSet<>(); // all values seen
    Set<E> dups = new HashSet<>(); // all values seen more than once
    for (E elt : list) {
        if (!seen.add(elt)) {
            // element not added--must have already been seen, so add to dups
            dups.add(elt);
        }
    }
    // clean out the list
    list.removeAll(dups);
    return list;

(三)使用set

public static <E> List<E> removeDuplicates(List<E> list){
    ListIterator<E> iter = list.listIterator();
    Set<E> seen = new HashSet<>();
    while (iter.hasNext()) {
        if (!seen.add(iter.next())) {
            // element not added--must have already been seen, so remove element
            iter.remove();
        }
    }
    return list;
}

(四)使用LinkedHashSet

public static <E> ArrayList<E> removeDuplicates(ArrayList<E> list2){
    LinkedHashSet<E> dataSet = new LinkedHashSet<E>(list2.size());
    dataSet.addAll(list2);
    ArrayList<E> uniqueLists = new ArrayList<E>(dataSet.size());
    uniqueLists.addAll(dataSet);
    return uniqueLists;
}

(五)

public static <E> ArrayList<E> removeDuplicates(ArrayList<E> list2){

    ArrayList<E> usedList = new ArrayList<E>();
    ArrayList<E> newList = new ArrayList<E>();

    for(int i = 0; i < list2.size(); i++){

        E object = list2.get(i);

        if(! usedList.contains(object))
        {
            usedList.add(object);
            newList.add(object);
        }
    }

    return newList;
}

(六)使用HashSet

HashSet hs<Integer> = new HashSet(list1);

ArrayList<Integer> uniqueList = Collections.sort(new ArrayList<Integer>(hs));

(七)使用HashSet

Set<Integer> aSet = new HashSet<Integer>(list);

list = new ArrayList<Integer>(new HashSet<Integer>(list));

沒有留言 :

張貼留言