我有一个ArrayList<String>,我想从它中删除重复的字符串。我该怎么做呢?


当前回答

像这样的东西会更好吗?

public static void removeDuplicates(ArrayList<String> list) {
    Arraylist<Object> ar     = new Arraylist<Object>();
    Arraylist<Object> tempAR = new Arraylist<Object>();
    while (list.size()>0){
        ar.add(list(0));
        list.removeall(Collections.singleton(list(0)));
    }
    list.addAll(ar);
}

这应该保持顺序,并且在运行时也不是二次的。

其他回答

如前所述,应该使用实现Set接口的类而不是List来确保元素的唯一性。如果必须保持元素的顺序,则可以使用SortedSet接口;TreeSet类实现了该接口。

用于自定义对象列表

   public List<Contact> removeDuplicates(List<Contact> list) {
    // Set set1 = new LinkedHashSet(list);
    Set set = new TreeSet(new Comparator() {

        @Override
        public int compare(Object o1, Object o2) {
            if (((Contact) o1).getId().equalsIgnoreCase(((Contact) o2).getId()) /*&&
                    ((Contact)o1).getName().equalsIgnoreCase(((Contact)o2).getName())*/) {
                return 0;
            }
            return 1;
        }
    });
    set.addAll(list);

    final List newList = new ArrayList(set);
    return newList;
}

在Java中,List允许对其元素进行有序访问。它们可以有重复,因为它们的查找键是位置而不是一些哈希代码,每个元素都可以被修改,而它们仍然在列表中,因为Set表示唯一元素的集合,而元素在Set中,它们不能被修改。虽然没有限制阻止您修改集合中的元素,但如果一个元素被修改,那么它可能永远丢失在集合中。

public static void main(String[] args) {
       List<String> l = new ArrayList<String>();
       l.add("A");
       l.add("B");
       l.add("C");
       l.add("A");
       System.out.println("Before removing duplicates: ");
       for (String s : l) {
            System.out.println(s);
       }
       Set<String> set = new HashSet<String>(l);
       List<String> newlist = new ArrayList<String>(set);
       System.out.println("after removing duplicates: ");
       for (String s : newlist) {
            System.out.println(s);
       }
  }

如需参考,请参考如何从ArrayList中删除重复项

在Java 8中:

List<String> deduped = list.stream().distinct().collect(Collectors.toList());

请注意,列表成员的hashCode-equals契约应该得到尊重,以便过滤正常工作。

虽然将ArrayList转换为HashSet可以有效地删除重复项,但如果您需要保留插入顺序,我宁愿建议您使用这个变体

// list is some List of Strings
Set<String> s = new LinkedHashSet<>(list);

然后,如果需要返回List引用,可以再次使用转换构造函数。