HashSet and Set
Set is a collection that contains unique items.
In this post, we will cover the way to convert a string array to Set<String>.
There are 2 approaches to do this requirement. Let’s consider which one we need to use.
1) Using new HashSet<>()
HashSet is a mutable collection. That means we can modify the set by adding or removing items. It receives the List<> as a parameter.
Let’s see the example:
String animals= "cat,dog,buffalo,cat,pig,dog,monkey,butterfly";
String str[] = animals.split(",");
Set<String> animalSet = new HashSet<>(Arrays.asList(str));
animalSet.forEach(item-> System.out.print(item + " --- ")); // result: monkey --- butterfly --- cat --- buffalo --- dog --- pig ---
animalSet.removeIf(item-> item.equals("buffalo") || item.equals("cat"));
animalSet.forEach(item-> System.out.print(item + " --- ")); // result: monkey --- butterfly --- dog --- pig ---
Arrays.asList(str) help us convert the string array to List String.
In the animals String, we have 2 items cats and 2 items dogs. After converting to Set we have a unique list of animal names.
As HashSet is the mutable collection, so we can remove an item at line 7.
2) Using Set.of()
Set.of() function only receives the unique items array. and the return value is an immutable collection. Meaning not allowing modification (add, remove items) from the set.
In the snippet code above if we replace:
Set animalSet = new HashSet<>(Arrays.asList(str));
by:
Set<String> animalSet = Set.of(str);
Then we will get the error:
Conclusions:
People refer to using the new HashSet<>(). But in some scenarios we use the Set.of() to verify the array whether unique or want to init an immutable collection.
Happy learning, happy coding. <3