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
package
blog.learnwebframeworks;
import
java.util.ArrayList;
import
java.util.Collections;
import
java.util.List;
public
class
SortArraList {
public
static
void
main(String[] args) {
List<String> mylist =
new
ArrayList<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 loop
for
(String names: mylist){
System.out.println(names);
}
//Sort the ArrayList using sort() from Collections class
Collections.sort(mylist);
System.out.println(
"***After sorting the arraylist***"
);
//iterate the list using for-each loop
for
(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 given
Iterator<string> it = mylist.iterator();
while
(it.hasNext()){
System.out.println(it.next());
}
0 comments :
Post a Comment