What is HashSet in java?
- HashSet class implements the Set interface, backed by a hash table.
- HashSet contains the unique elements.
- HashSet does not contains any duplicate keys
- HashSet can have only 1 null key.
- HashSet does not maintained the order of elements or keys.
- HashSet is UnSynchronized and not thread safe.
Program – Convert HashSet<String> to TreeSet<String>
package org.learn.collection.set.hset;
import java.util.HashSet;
import java.util.Set;
import java.util.TreeSet;
public class DemoHashSetToTreeSet {
public static void main(String[] args) {
Set<String> setSports = new HashSet<>();
setSports.add("Tennis");
setSports.add("Cricket");
setSports.add("Tennis");
setSports.add("Basketball");
setSports.add("Golf");
setSports.add("Boxer");
System.out.println("Set: "+ setSports);
Set<String> hashSetToTreeSet = new TreeSet<>(setSports);
System.out.println("TreeSet:"+hashSetToTreeSet);
}
}
Output – convert HashSet to TreeSet in java
Set: [Tennis, Cricket, Golf, Basketball, Boxer]
TreeSet:[Basketball, Boxer, Cricket, Golf, Tennis]