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.