Sorting any ArrayList is pretty simple. Using Collections.sort( )
 method we can sort the ArrayList. Collections class having all the 
static methods, we can use those methods directly along with the class 
name. These methods return the object as type Collection.
The important methods to synchronize the List, Set and Map as
The important methods to synchronize the List, Set and Map as
synchronizedList(List<T> list) synchronizedSet(Set<T> s) synchronizedMap(Map<K,V> m)
A simple program to sort an ArrayList
packageblog.learnwebframeworks;importjava.util.ArrayList;importjava.util.Collections;importjava.util.List;publicclassSortArraList {publicstaticvoidmain(String[] args) {List<String> mylist =newArrayList<String>();mylist.add("Mani");mylist.add("Bala");mylist.add("Kishore");mylist.add("Vijay");mylist.add("Vishnu");mylist.add("Manik");System.out.println("***Before sorting the arrylist***");//iterate the list using for-each loopfor(String names: mylist){System.out.println(names);}//Sort the ArrayList using sort() from Collections classCollections.sort(mylist);System.out.println("***After sorting the arraylist***");//iterate the list using for-each loopfor(String names: mylist){System.out.println(names);}}}Here we are using Collections.sort(mylist) method to sort our list. Here the list is iterating using for-each loop. By this we can get the elements one by one in a new line instead to displaying as an ArrayList. To display entire arraylist just we can use
System.out.println(mylist);it will displays the entire arrylist elements as[Mani, Bala, Kishore, Vijay, Vishnu, Manik]Collections class having a method to reverse the list isCollections.sort(mylist);Collections.reverse(mylist);System.out.println(mylist);if you want to iterate the arraylist without using Iterator loop you can as below givenIterator<string> it = mylist.iterator();
while(it.hasNext()){System.out.println(it.next());}
 
0 comments :
Post a Comment