1. 程式人生 > >java ArrayList去重複值

java ArrayList去重複值

    public static List 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);

            }

        }

        return newList;

    }

===========================

這樣利用set去了重複,又用linked保持住了原順序。 

returnnewArrayList<T>(newLinkedHashSet<T>(list));

========

    public static List removeDuplicateWithOrder(List list) { 
        List newList = new ArrayList(); 
        for (Object o : list) { 


            if (!newList .contains(o)) newList.add(o); 
        } 
        return newList; 
    } 

=======

    public static List removeDuplicateWithOrder(List list) {         Set set = new HashSet(list.size()); 
        set.addAll(list);         List newList = new ArrayList(set.size());         newList.addAll(set);         return newList;     }

=====

 Set<Object> set = new HashSet<Object>(list);