Java J2ME JSP J2EE Servlet Android

Java Sorting Array, List

Java provides an interface java.util.Collections which provides way to sort List, Arraylist etc. We can sort an array of String by first transforming it to a List first then applying Collection.sort() method then again transforming from List to String array. Here is a practical example of this. Hope this will be helpful to you.

String friends[] = {"Tuhin", "Sumon","Habib","Shishir","Kiser","Zimi","Lizzie"};
System.out.println(Arrays.toString(friends));
List tempList = Arrays.asList(friends);
System.out.println(tempList);
Collections.sort(tempList);
System.out.println(tempList);
friends = (String[]) tempList.toArray(new String[0]);
System.out.println(Arrays.toString(friends));

This code block if execute will generate output like ...

[Tuhin, Sumon, Habib, Shishir, Kiser, Zimi, Lizzie]
[Tuhin, Sumon, Habib, Shishir, Kiser, Zimi, Lizzie]
[Habib, Kiser, Lizzie, Shishir, Sumon, Tuhin, Zimi]
[Habib, Kiser, Lizzie, Shishir, Sumon, Tuhin, Zimi]