I am trying to find which numbers appear once in a list. For example, a list of [1, 3, 2, 3] should return [1, 2]. However, my code only returns [1], and when I also tried printing duplicates, it printed [3, 2].
I'm not sure where I'm going wrong since I'm keeping track of duplicates to ensure that I don't count an element twice.
Is there also a more efficient way to do this? For example, with a HashMap? I know there's the Collections class that I can use but I'd rather avoid that, for practice!
Any help and advice would be appreciated.
This is what I have below:
import java.util.*;
class Main {
public static void main(String[] args) {
// From a list find which numbers appear once
ArrayList<Integer> list = new ArrayList<Integer>();
list.add(1);
list.add(3);
list.add(2);
list.add(3);
ArrayList<Integer> once = new ArrayList<Integer>();
boolean isDuplicate = false;
ArrayList<Integer> duplicate = new ArrayList<Integer>();
for (int i=0; i<list.size(); i++) {
if (!duplicate.contains(list.get(i))){ // if its not a duplicate, continue iterating through the list
for (int j=i+1; j<list.size(); j++) {
if (list.get(i).equals(list.get(j))) { // if its a duplicate
isDuplicate = true;
}
}
if (!isDuplicate) { // if its not a duplicate add to the "once" list
once.add(list.get(i));
} else { // if isDuplicate is true add to the duplicate list
duplicate.add(list.get(i));
}
}
}
System.out.println("Numbers that appear once: " + once + "\nDuplicates: " + duplicate);
}