how to Iterate through an arrayList of object and

2019-07-22 15:34发布

问题:

I have the following class:

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

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...

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]

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!

Thanks!

回答1:

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).