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


当前回答

如果您使用的模型类型为List< T>/ArrayList< T>。希望,它能帮到你。

下面是我的代码,没有使用任何其他数据结构,如set或hashmap

for (int i = 0; i < Models.size(); i++){
for (int j = i + 1; j < Models.size(); j++) {       
 if (Models.get(i).getName().equals(Models.get(j).getName())) {    
 Models.remove(j);
   j--;
  }
 }
}

其他回答

在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中删除重复项

用于自定义对象列表

   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;
}

如果不希望集合中有重复项,则应该考虑为什么要使用允许重复项的集合。删除重复元素最简单的方法是将内容添加到Set(不允许重复),然后将Set添加回ArrayList:

Set<String> set = new HashSet<>(yourList);
yourList.clear();
yourList.addAll(set);

当然,这破坏了数组列表中元素的顺序。

假设我们有一个字符串列表,像这样:

List<String> strList = new ArrayList<>(5);
// insert up to five items to list.        

然后我们可以用多种方式删除重复的元素。

Java 8之前

List<String> deDupStringList = new ArrayList<>(new HashSet<>(strList));

注意:如果我们想保持插入顺序,那么我们需要使用LinkedHashSet来代替HashSet

使用番石榴

List<String> deDupStringList2 = Lists.newArrayList(Sets.newHashSet(strList));

使用Java 8

List<String> deDupStringList3 = strList.stream().distinct().collect(Collectors.toList());

注意:如果我们想在一个特定的列表实现中收集结果,例如LinkedList,那么我们可以修改上面的例子:

List<String> deDupStringList3 = strList.stream().distinct()
                 .collect(Collectors.toCollection(LinkedList::new));

我们也可以在上面的代码中使用parallelStream,但它可能不会带来预期的性能优势。查看这个问题了解更多信息。

for(int a=0;a<myArray.size();a++){
        for(int b=a+1;b<myArray.size();b++){
            if(myArray.get(a).equalsIgnoreCase(myArray.get(b))){
                myArray.remove(b); 
                dups++;
                b--;
            }
        }
}