i am having a string arraylist 'names'.which contains names of people.i want to sort the arraylist in alphabetical order.plz help me
This will solve your problem...
ArrayList arrayList = new ArrayList();
//Add elements to Arraylist
arrayList.add("1");
arrayList.add("3");
arrayList.add("5");
arrayList.add("2");
arrayList.add("4");
Collections.sort(arrayList);
//display elements of ArrayList
System.out.println("ArrayList elements after sorting in ascending order : ");
for(int i=0; i<arrayList.size(); i++)
System.out.println(arrayList.get(i));
To sort an ArrayList object, use Collection.sort
method. This is a
static method. It sorts an ArrayList object's elements into ascending order.
Just in case if the below code in comment doesnt work means...
Try this code..
Create a custom comparator class:
import java.util.Comparator;
class IgnoreCaseComparator implements Comparator<String> {
public int compare(String strA, String strB) {
return strA.compareToIgnoreCase(strB);
}
}
Then on your sort:
IgnoreCaseComparator icc = new IgnoreCaseComparator();
java.util.Collections.sort(arrayList,icc);
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;
public class ArrayListSortExample {
public static void main(String[] args) {
/*
* Create a collections of colours
*/
List colours = new ArrayList();
colours.add("red");
colours.add("green");
colours.add("blue");
colours.add("yellow");
colours.add("cyan");
colours.add("white");
colours.add("black");
/*
* We can sort items of a list using the Collections.sort() method.
* We can also reverse the order of the sorting by passing the
* Collections.reverseOrder() comparator.
*/
Collections.sort(colours);
System.out.println(Arrays.toString(colours.toArray()));
Collections.sort(colours, Collections.reverseOrder());
System.out.println(Arrays.toString(colours.toArray()));
}
hi seethalakshmi for sorting on Arraylist you need comparator and collection
just go through this link http://ventrix.nsdc.gr/code_folds/?p=119, you can easily implement it
精彩评论