I am trying to find the number of Strings that only appear exactly once in an `ArrayList`.

How many I achieve this (preferably with the best possible time complexity)?

Below is my method:

```
  public static int countNonRepeats(WordStream words) {

    ArrayList<String> list = new ArrayList<String>();
    for (String i : words) {
      list.add(i);
    }

    Collections.sort(list);

    for (int i = 1; i < list.size(); i++) {
      if (list.get(i).equals(list.get(i - 1))) {
        list.remove(list.get(i));
        list.remove(list.get(i - 1));
      }
    }

    System.out.println(list);

    return list.size();
  }

```

Why doesn't it remove the String at `list.get(i)` and `list.get(i-1)`?
['https://Stackoverflow.com/questions/35996096', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/5938067/']
Is there any specific need of using an `ArrayList`? You can do it easily by using a `HashSet`.

Here is the code snippet:

```
public static void main (String[] args) {
    String[] words = {"foo","bar","foo","fo","of","bar","of","ba","of","ab"};
    Set<String> set = new HashSet<>();
    Set<String> common = new HashSet<>();
    for (String i : words) {
        if(!set.add(i)) {
            common.add(i);
        }
    }

    System.out.println(set.size() - common.size());
}

```

Output:

```
3

```

Here is the modified code:

```
public static int countNonRepeats(WordStream words) {
    Set<String> set = new HashSet<>();
    Set<String> common = new HashSet<>();
    for (String i : words) {
        if(!set.add(i)) {
            common.add(i);
        }
    }

    return (set.size() - common.size());
}

```
You can use hashmap to achieve this.With this approach we can count the occurrence of all the words,  
 If we are interested in only unique words then access the element having count = 1.   

**`HashMap<String,Integer>`** - key represents the String from arraylist and Integer represents the count of occurrence.  

```
        ArrayList<String> list = new ArrayList<String>();
        HashMap<String, Integer> hashMap = new HashMap<String, Integer>();

        for (int i = 0; i < list.size(); i++) {

            String key = list.get(i);

            if (hashMap.get(key) != null) {
                int value = hashMap.get(key);
                value++;
                hashMap.put(key, value);
            } else {
                    hashMap.put(key, 1);
            }

        }
        int uniqueCount = 0;
        Iterator it = hashMap.entrySet().iterator();
        while (it.hasNext()) {
            Map.Entry pair = (Map.Entry) it.next();
            if ((int) pair.getValue() == 1)
                uniqueCount++;
        }
        System.out.println(uniqueCount);

```