See Example:
import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
import java.util.TreeSet;
public class Example1 {
public static void main(String args[]) {
// HashSet declaration
HashSet<String> hashset = getHashSet();
}
public static HashSet<String> getHashSet(){
HashSet<String> hashset = new HashSet<String>();
// Adding elements to the HashSet
hashset.add("Item4");
hashset.add("Item2");
hashset.add("Item6");
hashset.add("Item1");
hashset.add("Item3");
hashset.add("Item5");
System.out.println("HashSet values : ");
for(String str : hashset){
System.out.println(str);
}
// Creating a TreeSet of HashSet elements
Set<String> treeset = new TreeSet<String>(hashset);
// Displaying TreeSet elements
System.out.println("TreeSet values : ");
for(String temp : treeset){
System.out.println(temp);
}
return hashset;
}
}
//result :
HashSet values :
Item1
Item2
Item5
Item6
Item3
Item4
TreeSet values :
Item1
Item2
Item3
Item4
Item5
Item6
we saw the values of TreeSet is sorted.
EmoticonEmoticon