如何遍历对象的arrayList并在对象属性中查找重复项? [英] how to Iterate through an arrayList of object and find duplicates in object properties?

查看:44
本文介绍了如何遍历对象的arrayList并在对象属性中查找重复项?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有以下课程:

class A {
    ArrayList<String> s = new ArrayList<>();
    double d = Double.MAX_VALUE;
}

我有一个 A 类的数组列表,例如 ArrayListalist = new ArrayList<>();alist 我有一些如下元素:

I've an arrayList of class A like ArrayList<A> alist = new ArrayList<>(); In alistI have some elements like followings:

[[b  c]  1.3]
[[c  d]  0.2]
[[c  b  o]  0.9]
[[x  o  j]  1.8]
[[c  d]  1.7]
[[b  c  o]  2.2]
[[f  p  n]  1.1]
and so on...

我需要的只是遍历这个 alist 并检查 class A 对象的 String 列表中是否有任何重复项.如果是这样,则只保留一个元素并使用其 d 值添加其他 d 值,并从 alist 中删除具有相同字符串列表的其他元素.例如:
从上面的列表中我们可以看到第 2 个和第 5 个元素具有重复的字符串列表,因此添加它们的值并仅保留其中一个具有该添加值并删除其他元素.同理,第 3 和第 6 元素具有相同的字符串列表(字符串顺序在内部字符串列表中不重要).所以对于上面的列表,预期的输出将是:

All I need is to iterate through this alistand check if there any duplicates in String list of class A object. If so then preserve only one element and add others d values with its d value and remove other elements from alistwhich have the same String list. For example:
from the above list we can see 2nd and 5th elements have duplicate string list so add their values and preserve only one of them with that added value and remove others. Same as, element 3rd and 6th has same String list(string order is not important in inner string list). So for the above list, the expected output will be:

[[b  c]  1.3]
[[c  d]  1.9]
[[b  c  o]  3.1]
[[x  o  j]  1.8]
[[f  p  n]  1.1]

有人可以通过提供一些示例代码来帮助我吗?我不太擅长 Java.所以如果我犯了任何错误,请原谅我!

Can anybody help me with this by providing some sample code please? I'm not that good in Java. So please pardon me if I made any mistake!

谢谢!

推荐答案

一个好的起点是定义 .equals() 方法在类 A 中的作用.然后它就像迭代你的集合一样简单,并且询问是否 a.eqauls(b).

A good place to start would be defining what the .equals() method does in class A. Then it is just as easy as iterating over your collection, and asking if a.eqauls(b).

这篇关于如何遍历对象的arrayList并在对象属性中查找重复项?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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