Reputation: 4333
I'm going through Java Collections
in Oracle Docs Java. I'm not able to figure out few lines of code from the below.
This program splits the duplicate words, unique words.
public class FindDups {
public static void main(String[] args) {
Set<String> uniques = new HashSet<String>();
Set<String> dups = new HashSet<String>();
for (String a : args)
if (!uniques.add(a))
dups.add(a);
// Destructive set-difference
uniques.removeAll(dups);
System.out.println("Unique words: " + uniques);
System.out.println("Duplicate words: " + dups);
}
}
I'm not able to get these lines. Can anyone explain, what is actually happening here?
for (String a : args) if (!uniques.add(a)) dups.add(a);
Upvotes: 2
Views: 328
Reputation: 57124
From the docs regarding add
:
Returns: true if this set did not already contain the specified element
That means the code "tries" to insert the object into uniques
and if the add
returns false
the object was already there, meaning it is actually a duplicate - therefore it gets inserted into dups
if uniques.add
is false
.
Afterwards all entries in dups
get removed from uniques
:
uniques.removeAll(dups);
After that uniques
only contains the Strings present only once while dups
contains all Strings that occurred multiple times.
Upvotes: 2
Reputation: 22089
From the Oracle docs for the add
method of Set
:
true
if this set did not already contain the specified element
So what the code does is:
for (String a : args)
: Iterate over all the input strings stored in the args
array.if (!uniques.add(a))
: If the add method returns true
, the string is unique and successfully added to the Set
uniques
, as it is not contained, yet (see docs). Otherwise, the add
method returns false
(the current string a
is already contained in the Set
uniques
) so...dups.add(a);
: ...add it to the Set
of duplicate elements.As a note for a beginner, a Set
can only contain an individual element once. So, if a
is already in uniques
, the call uniques.add(a)
will just return true
, but not actually add anything. If not, the element is added and it returns false
.
Upvotes: 2
Reputation: 61
if (!uniques.add(a))
uniques.add(a) will return True if the word that was added was NOT in the set already. False if it is inside it (this method has a return of type Boolean).
dups.add(a);
So if it sees that the word is already in the set, it will add it to the dupes set.
Hope that helps!
Upvotes: 1