I have a List of integer’s with duplicate values in it. What I need to do is find the duplicate integers, add their value and then add the result to the list by removing the duplicates found. Here is what I am doing:
List<Integer> list1 = new ArrayList<Integer>();
list1.add(2);
list1.add(5);
list1.add(3);
list1.add(5);
list1.add(4);
List<Integer> list2 = new ArrayList<Integer>();
Iterator<Integer> it = list1.iterator();
while (it.hasNext()) {
Integer int1 = it.next();
if (list2.isEmpty()) {
list2.add(int1);
it.remove();
} else {
ListIterator<Integer> it2 = list2.listIterator();
while (it2.hasNext()) {
Integer int2 = it2.next();
if (int2 != int1) {
it2.add(int1);
it.remove();// I get exception here
} else {
it2.remove();
it.remove();
Integer newint = int1 + int2;
it2.add(newint);
}
}
}
}
for(Integer in : list2){
System.out.println(in);
}
Output should look like
2
10
3
4
Thanks for your time.
If you are allowed to use a Map you could do something simple like this (incoming pseudocode):
Your result are the values of m (which is a Collection).
Edit: You said you have LatLng instead of Integers – I don’t know LatLng but after a quick google I’d take a shot at the following, assuming that you want to “add” up your LatLng points:
The only problem I can see here is that this
m.containsKey(x)depends on the correct implementation ofequals, which I’m not sure after reading this