Java examples for java.util:List Operation
remove Duplicates from List
/*/*from ww w .j a v a 2 s .co m*/ * Copyright 2001-2008 Aqris Software AS. All rights reserved. * * This program is dual-licensed under both the Common Development * and Distribution License ("CDDL") and the GNU General Public * License ("GPL"). You may elect to use one or the other of these * licenses. */ import java.util.ArrayList; import java.util.Comparator; import java.util.List; public class Main { public static void main(String[] argv) { List list = java.util.Arrays.asList("asdf", "java2s.com"); removeDuplicates(list); } public static final void removeDuplicates(List list) { List duplicatesToRemove = new ArrayList(); for (int i = 0; i < list.size(); i++) { final Object first = list.get(i); for (int k = i + 1; k < list.size(); k++) { if (i != k) { final Object second = list.get(k); if (first.equals(second)) { addNew(duplicatesToRemove, second); } } } } for (int i = 0; i < duplicatesToRemove.size(); i++) { final Object duplicate = duplicatesToRemove.get(i); list.remove(duplicate); } } public static final void removeDuplicates(List list, Comparator comparator) { List duplicatesToRemove = new ArrayList(); for (int i = 0; i < list.size(); i++) { final Object first = list.get(i); for (int k = i + 1; k < list.size(); k++) { if (i != k) { final Object second = list.get(k); if (comparator.compare(first, second) == 0) { duplicatesToRemove.add(second); // CollectionUtil.addNew(duplicatesToRemove, second, comparator); } } } } list.removeAll(duplicatesToRemove); } public static final List addNew(List list, Object object) { if (!list.contains(object)) { list.add(object); } return list; } }