gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-29 05:43:26 25 4
gpt4 key购买 nike

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

2550111.551, 3
3550111.551, 2, 3
2155.551, 2
3550111.552, 3, 1
2155.552, 1
2550111.553, 1
3550111.553, 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

3550111.553, 1, 2

and

3550111.551, 2, 3

and

3550111.552, 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:

3550111.552, 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/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com