Skip to main content

Post 3: Core Java: How to sort an ArrayList


How to sort an ArrayList in java

ArrayList are also called as dynamic arrays that can grow as needed. In Java ArrayList class extends AbstractList and implements List interface. In Java ArrayList’s are created with an initial size. The size of the collection is changes dynamically as the items are exceeded the size or deleted. This example will explain sorting of ArrayList using Comparator, Comparable and Collectiolns.sort() method.
Note: Typically standard Array in java is fixed sized in nature. Once created, they cannot grow or shrink, which means that you must know in advance how many elements an array will hold.
At times, you may need to sort the ArrayList to make it alphabetically order. In this below example, it shows the use of Collections.sort and comparator to sort an ArrayList.

1. Sorting using Collections.sort method:

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
public class SortArrayList {
 
 public static void main(String[] args) {
  ArrayList unsortList = new ArrayList();
  unsortList.add("1011");
  unsortList.add("5460");
  unsortList.add("1000");
  unsortList.add("Abdul");
  unsortList.add("1012");
  unsortList.add("Adam");
 
  System.out.println("********** Value before sorting **************");
  for (String str : unsortList) {
   System.out.println(str);
  }
 
  Collections.sort(unsortList);
 
  System.out.println("********** Value after sorting **************");
  for (String str : unsortList) {
   System.out.println(str);
  }
 
 }
}
Here in this above example the sorting happens according to ASCII.
Output:
sorting-array-list-using-collections.sort

 2. Sorting objects in an ArrayList using Comparable interface

In my example I want to sort the employees list as per their salary in descending order. My Employee class implements Comparable interface and overridden compareTo method. In Compare to method add your logic, weather to sort ascending or descending order.
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
39
40
41
42
43
44
45
46
47
48
49
50
51
52
public class Employee implements Comparable {
 private String name;
 private String id;
 private double salary;
 
 public Employee(String id, String name, double salary) {
  this.id = id;
  this.name = name;
  this.salary = salary;
 }
 
 public String getName() {
  return name;
 }
 
 public void setName(String name) {
  this.name = name;
 }
 
 public String getId() {
  return id;
 }
 
 public void setId(String id) {
  this.id = id;
 }
 
 public double getSalary() {
  return salary;
 }
 
 public void setSalary(double salary) {
  this.salary = salary;
 }
 
 @Override
 public int compareTo(Employee emplyoee) {
  double compareSalary = ((Employee) emplyoee).getSalary();
 
  // ascending order
  // return (int) (this.salary - compareSalary);
 
  // descending order
  return (int) (compareSalary - this.salary);
 }
 
 @Override
 public String toString() {
  return "[ id=" + id + ", name=" + name + ", salary=" + salary + "]";
 }
 
}

3. Sorting Objects in an ArrayList using Comparator

Check out the below code snippet, I am sorting Employees list using Anonymous Comparator
1
2
3
4
5
6
7
8
9
10
11
12
13
14
//Sorting using Anonymous inner class type
  Collections.sort(emplyoees, new Comparator() {
   @Override
   public int compare(Employee e1, Employee e2) {
    String id1 = ((Employee) e1).getId();
    String id2 = ((Employee) e2).getId();
 
    // ascending order
     return id1.compareTo(id2);
 
    // descending order
    //return id2.compareTo(id1);
   }
  });
Complete Code
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
39
40
41
42
43
44
public class SortArrayListObjects {
 
 public static void main(String[] args) {
 
  ArrayList emplyoees = new ArrayList();
  emplyoees.add(new Employee("1001", "Adam", 5000));
  emplyoees.add(new Employee("1006", "Rajan", 8400));
  emplyoees.add(new Employee("1040", "Keay", 2500));
  emplyoees.add(new Employee("1056", "Ashok", 12000)); 
 
  System.out.println("**** Value before sorting ***");
  for(Employee emplyoee: emplyoees){
   System.out.println(emplyoee);
  }
 
  Collections.sort(emplyoees);
 
  System.out.println("**** After sorting salary decending ***");
  for(Employee emplyoee: emplyoees){
   System.out.println(emplyoee);
  }
 
  //Sorting using Anonymous inner class type
  Collections.sort(emplyoees, new Comparator() {
   @Override
   public int compare(Employee e1, Employee e2) {
    String id1 = ((Employee) e1).getId();
    String id2 = ((Employee) e2).getId();
 
    // ascending order
     return id1.compareTo(id2);
 
    // descending order
    //return id2.compareTo(id1);
   }
  });
 
  System.out.println("**** After sorting id accending ***");
  for(Employee emplyoee: emplyoees){
   System.out.println(emplyoee);
  }
 
 }
}
Outputsorting-array-list-using-Comparator

Comments

Popular posts from this blog

TIME TABLE: VTU BE/B.Tech June/July 2016 Exam Time table Draft Layout

Semester-wise June-July 2016 Exam time table (Draft Layout) Are You Using updated Kwikstudy App?

Walkins Bangalore: 01st-Oct-2016

1. UTC Aerospace : GET – S&IS-Software Team hiring Electronics & CSE / IT Freshers ! Walkin on 1st OCT | BE/BTECH - 2015 & 2016 both batch can try Selection Process : Written Test Group Discussion Technical & HR Interviews How To Apply : It is a walk-in drive for 2016 batch eligible freshers on 1 Oct 2016 at Bangalore location. Interested and eligible candidates can walk-in to the following venue on 1 Oct 2016 Date of Drive : 01 Oct 2016 Reporting Time : 8:00 AM to 11:30 AM Venue : UTC Aerospace Systems – Site 1, Sy. Nos. 14/1 & 15/1, Maruthi Industrial State, Phase 2, Hoody Village, Whitefield Road, K R Puram Hobli, Bangalore – 560048 ______________________________________ 2. HP : Software Eng/ Software Tester (Call based ,less chance of getting entry , try at your own risk) Event Date : 1-October-2016 Event Time : 8 : 00 am Job Location : Bangalore / Chennai Job Description: Software Engineer /

How to get VTU Provisional Degree Certificate (PDC) ?

Here is the procedure to get the Provisional Degree Certificate from the VTU by passed out candidates. You can get the certificate through post by sending the required documents to VTU. Documents and things required: 1. Provisional Degree Certificate (PDC) application form 2. DD of specified fees amount or print copy of receipt if you paid the fees online 3. A letter to the VTU registrar 4. A4 size envelope Step 1: Fill the PDC application You can download the PDC application form from the VTU website. Click below link for application download. PDC application form download     After downloading the application take a print of it and properly fill the form. Step 2: Make a DD of specified amount as the fees of PDC: Go to the bank and make the DD of prescribed fee amount for the PDC. The fee amount is specified in the above link from where you downloaded the application. Make the DD in favor of " Finance Officer, VTU Belgaum ".   Wr