删除ArrayList中的重复项-Java [英] Remove duplicates in ArrayList - Java

查看:82
本文介绍了删除ArrayList中的重复项-Java的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的Java代码有问题.我应该使用循环而不是其他任何方法. 假设我的ArrayLis t包含

I have some problem with my Java code. I'm supposed to use loops and not any other method. Say that my ArrayList contains of

[狗猫狗狗猫狗马]

[Dog Cat Dog Dog Cat Dog Horse]

我的目标也是删除狗"和猫"的副本,以使我的最终结果等于

My goal is also to remove the copies of Dog and Cat so my final results equals

[狗猫马]

[Dog Cat Horse]

public void removeDouble(){

int counter = 0;
for (int i = 0 ; i < animals.size(); i++) { 
    for (int j = 1+i;  j < animals.size() ; j++)  
        //don't start on the same word or you'll eliminate it.
        if ( animals.get(j).equals( animals.get(i) )  ) {
            animals.remove(animals.get(j));
           counter++;

        }                                
    } 
}

感觉逻辑"是正确的,但是我的代码不能很好地工作.有人可以帮我一下吗?

It feels like the "logic" is correct but my code does not work very well. Can somebody help me a little?

推荐答案

您可以这样做.

 ArrayList<String>list=new ArrayList<>();
    list.add("A");
      list.add("B");
      list.add("C");
      list.add("A");
    System.out.println("Before "+list); // output[A,B,C,A]


    Set<String> listWithoutDuplicates = new LinkedHashSet<String>(list);
     list.clear();

    list.addAll(listWithoutDuplicates);
    System.out.println("list without duplicates : " + list);// output[A,B,C]

这篇关于删除ArrayList中的重复项-Java的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆