ZeldaX ZeldaX - 1 month ago 6
Java Question

Iterating through sets

I am writing a program that will receive a list of words. After that, it will store the repeated words and the non repeated into two different lists. My code is the following:

public class Runner
{
public static void run (Set<String> words)
{

Set<String> uniques= new HashSet<String>();

Set<String> dupes= new HashSet<String>();

Iterator<String> w = words.iterator();

while (w.hasNext())
{
if (!(uniques.add(w.next())))
{
dupes.add(w.next());
}
else
{
uniques.add(w.next());
}


}

System.out.println ("Uniques: "+ uniques);
System.out.println ("Dupes: "+ dupes);



}

}


However, the output for the following:


right, left, up, left, down


is:


Uniques: [left, right, up, down]

Dupes: []


and my desired would be:


Uniques: [right, left, up, down]

Dupes: [ left ]


I want to achieve this using sets. I know it would be way easier to just an ArrayList but I am trying to understand sets.

Answer

The reason for your problem is that the argument words is a Set<String>. A set by definition will not contain duplicates. The argument words should be a List<String>. The code also makes the mistake of calling w.next() twice. A call to the next() will cause the iterator to advance.

public static void run(List<String> words>) {
    Set<String> uniques= new HashSet<String>();
    Set<String> dupes= new HashSet<String>();
    Iterator<String> w = words.iterator();
    while(w.hasNext()) {
         String word = w.next();
         if(!uniques.add(word)) {
             dupes.add(word);
         }
    }
}