Generally, sets are a type of collection which stores unique values. Uniqueness is determined by the equals()
and hashCode()
methods.
Sorting is determined by the type of set.
HashSet
- Random SortingSet<String> set = new HashSet<> ();
set.add("Banana");
set.add("Banana");
set.add("Apple");
set.add("Strawberry");
// Set Elements: ["Strawberry", "Banana", "Apple"]
LinkedHashSet
- Insertion OrderSet<String> set = new LinkedHashSet<> ();
set.add("Banana");
set.add("Banana");
set.add("Apple");
set.add("Strawberry");
// Set Elements: ["Banana", "Apple", "Strawberry"]
TreeSet
- By compareTo()
or Comparator
Set<String> set = new TreeSet<> ();
set.add("Banana");
set.add("Banana");
set.add("Apple");
set.add("Strawberry");
// Set Elements: ["Apple", "Banana", "Strawberry"]
Set<String> set = new TreeSet<> ((string1, string2) -> string2.compareTo(string1));
set.add("Banana");
set.add("Banana");
set.add("Apple");
set.add("Strawberry");
// Set Elements: ["Strawberry", "Banana", "Apple"]