How to sort element of ArrayList

For List type of collection you can use Collections.sort(..) method.

Sorting Integer type

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
29
30
31
package com.spy.javaforlearn;
 
import java.util.ArrayList;
import java.util.Collections;
 
public class SortArraylist
{
	public static void main(String[] args) 
	{
 
		//Integer arraylist
 
		ArrayList<Integer> list=new ArrayList<Integer>();
 
		list.add(5);
		list.add(2);
		list.add(1);
		list.add(3);
		list.add(4);
 
		Collections.sort(list);
 
		for (Integer integer : list) 
		{
 
			System.out.println(integer);
 
		}
 
	}
}

Output:

1
2
3
4
5
1
2
3
4
5

Sorting String type

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
29
30
31
32
33
34
35
36
37
38
package com.spy.javaforlearn;
 
import java.util.ArrayList;
import java.util.Collections;
 
public class sortingArraylist 
{
	public static void main(String[] args) 
	{
		//Arraylist of String
 
        ArrayList<String> list=new ArrayList<String>();
 
 
			list.add("Bhavesh");
 
			list.add("Abhi");
 
			list.add("vivek");
 
			list.add("milan");
 
 
	    Collections.sort(list);
 
 
	   // Retrieving Arraylist element
 
	    for(String name:list)
	    {
 
	    	System.out.println(name);
 
	    }
 
	}
 
}

output:

1
2
3
4
	Abhi
	Bhavesh
	milan
	vivek

Leave a Reply

Your email address will not be published. Required fields are marked *