How to sort HashSet using Arrays.sort()


import java.util.Set;
import java.util.HashSet;
import java.util.Arrays;

public class SetSorting{
public static void main(String args[]){

/*Creating HashSet*/
Set hSet = new HashSet();

Integer[] intArray = new Integer[10];

intArray[0]= new Integer(11);
intArray[1]= new Integer(22);
intArray[2]= new Integer(3);
intArray[3]= new Integer(3);
intArray[4]= new Integer(7);
intArray[5]= new Integer(17);
intArray[6]= new Integer(6);
intArray[7]= new Integer(13);
intArray[8]= new Integer(0);
intArray[9]= new Integer(1);


/*Adding Elements*/
hSet.add(intArray[0]);
hSet.add(intArray[1]);
hSet.add(intArray[2]);
hSet.add(intArray[3]);
hSet.add(intArray[4]);
hSet.add(intArray[5]);
hSet.add(intArray[6]);
hSet.add(intArray[7]);
hSet.add(intArray[8]);
hSet.add(intArray[9]);

System.out.println("Elements Before Sorting:");

for(Integer intVal:hSet){
System.out.println(intVal.intValue());
}

/*Using Arrays.sort()*/
Integer[] setArray = new Integer[0];
setArray = hSet.toArray(setArray);
Arrays.sort(setArray);

System.out.println("Elements After Sorting:");

for(Integer intVal:setArray){
System.out.println(intVal.intValue());
}

}
}

Output:

Elements Before Sorting:
0
17
1
3
6
7
22
11
13
Elements After Sorting:
0
1
3
6
7
11
13
17
22


I would like to know your comments and if you liked the article then please share it on social networking buttons.


No comments:

Post a Comment