Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

sorting arraylist of string in android [duplicate]

Tags:

java

android

i am having a string arraylist 'names'.which contains names of people.i want to sort the arraylist in alphabetical order.plz help me

like image 447
andro-girl Avatar asked Apr 28 '11 07:04

andro-girl


2 Answers

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); 
like image 193
Hussain Avatar answered Sep 19 '22 12:09

Hussain


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()));
}
like image 31
evilone Avatar answered Sep 20 '22 12:09

evilone