Pages

Tuesday, 10 September 2013

How to sort ArrayList in java, Sorting java Collections



let us see how to sort values in java collections, List/ArrayList.  We can achieve this by using Collections class, Collections class contains a method sort(Collection Object), just give your collection object to the sort() method that’s it, consider this example….

SortCollection.java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
package java4s;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;

public class SortCollection {

    public static void main(String... args)
    {

            List li = new ArrayList();

            li.add("India");
            li.add("United States");
            li.add("Malaysia");
            li.add("Australia");
            li.add("Lundon");

            Collections.sort(li);

            for(String temp: li)
            {
                System.out.println("Countries : "+temp);
            }
    }
}
Output
Countries : Australia
Countries : India
Countries : Lundon
Countries : Malaysia
Countries : United States

No comments:

Post a Comment