java - 从 ArrayList 中删除重复的字符串

标签 java

我有一个包含重复元素的 StringsArrayList。每 3 行构成一个实体:

2
550111.55
1, 3
3
550111.55
1, 2, 3
2
155.55
1, 2
3
550111.55
2, 3, 1
2
155.55
2, 1
2
550111.55
3, 1
3
550111.55
3, 1, 2

All the elements are Strings. The first number says the number of participants, the second says the value, and the third which elements make it up. So I have duplicates like

3
550111.55
3, 1, 2

and

3
550111.55
1, 2, 3

and

3
550111.55
2, 3, 1

The number of elements says the number of duplicates, so I must remove all the duplicates, in this case, delete all but one instance, for example:

3
550111.55
2, 3, 1

I am trying to do it like this :

ArrayList<String> lista_rezultata1=new ArrayList<String>();
lista_rezultata1=lista_rezultata;
//set to count to 3 in arraylist since data I need to split and evaluate are always on the third place
int number1=0;
int number2=0;
String[] part1=null;
String[] part2=null;
int removefromlist=0;
for (int i = 0; i < lista_rezultata.size(); i++) {
    if(number1==3)number1=0;
    if(number1==2)//If it is a third element it is the one with "," that I split
    {
        part1=lista_rezultata.get(i).toString().split(",");
    }

    for (int j = 0; j < lista_rezultata1.size(); j++) {
        if(number2==3)number2=0; 

        if(number2==2 && i!=j && number1==2)//If it is a third element it is the one with "," that I split, first must already be splited
        {
            part2=lista_rezultata1.get(j).toString().split(",");

            for (int k = 0; k < part1.length; k++) {
                for (int l = 0; l < part2.length; l++) {
                    if(part1.length==part2.length)   //if they have the same number of elements
                    { 
                        if(part2[l].equals(part1[j]))
                        {
                            .....some code
                        }
                    }
                }
            }
        }

        number2=number2+1;   
    }
    number1=number1+1; 
}

所以我希望有更好的方法......

最佳答案

恐怕你的方法是错误的......

  • 创建一个类来表示您的项目
  • 覆盖 equals()返回 true 的方法如果您的商品值(value)相同
  • 覆盖 hashCode()产生int的方法值基于您在 equals() 中比较的相同值方法(因此 hashCode“同意”等于)
  • 使用 Set<Item>保存您的元素 - 套装使用 equals()确保没有重复

您可能希望使用 LinkedHashSet 为你Set实现:

Set<Item> set = new LinkedHashSet<Item>();

A LinkedHashSet将确保其元素的迭代顺序与其插入顺序相同。

关于java - 从 ArrayList 中删除重复的字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16681707/

相关文章:

java - 有没有方法初始化之类的东西?

java - 错误 com.mysql.jdbc.exceptions.jdbc4.CommunicationsException : Communications link failure

java - 如何在 Java 中修复此死锁代码?

java - 第一个 servlet,但无法打开它

java - RecyclerAdapter getItemCount 崩溃

java - 跨项目共享 hibernate 配置的最佳方式

C# SOAP 网络服务和 Java 客户端

javax.lang.模型 : How do I get the type of a field?

java - 有谁知道我为什么会收到此 IllegalMonitorStateException?

java - 统计变量设计问题的类