Different sorting methods for Java ArrayList

  • 2020-04-01 04:31:04
  • OfStack

Because of its functionality and flexibility, ArrayList is one of the most commonly used collection classes in the Java collections framework. ArrayList is a List implementation that internally stores elements in a dynamic array, so ArrayList can be dynamically expanded and shrunk as elements are added and removed. You've probably already used an ArrayList, so I'll skip the basics. If you are not familiar with the ArrayList, you can refer to its API documentation, and you can easily understand how to perform basic operations on the ArrayList.
In this article, I'll discuss an extremely important operation in the ArrayList that you will most likely need to implement in enterprise application development. It's the sort of ArrayList elements.

Sort the ArrayList of the string object

Consider an ArrayList that stores the country name as a string. To sort the ArrayList, you need to call the collections.sort () method, passing the ArrayList object with the country name. This method sorts the elements (country names) in their natural order (alphabetically ascending). Let's write a piece of code for this.
SortArrayListAscendingDescending. Java


package guru.springframework.blog.sortarraylist.ascendingdescending;
 import java.util.ArrayList;
 import java.util.Collections;
 public class SortArrayListAscendingDescending {
 private ArrayList arrayList;
 public SortArrayListAscendingDescending(ArrayList arrayList) {
 this.arrayList = arrayList;
 }
 public ArrayList getArrayList() {
 return this.arrayList;
 }
 public ArrayList sortAscending() {
 Collections.sort(this.arrayList);
 return this.arrayList;
 }
 public ArrayList sortDescending() {
 Collections.sort(this.arrayList, Collections.reverseOrder());
 return this.arrayList;
 }
 }

In the above class, we initialize an ArrayList object in the constructor. In the sortAscending() method, we call the collections.sort () method, pass the initialized ArrayList object as a parameter, and return the sorted ArrayList. In the sortDescending() method, we call the overloaded collections.sort () method to sort the elements in descending order. This version of collections.sort () receives the ArrayList object as the first argument, and a Comparator object returned by the collections.reverseorder () method as the second argument. We'll talk about comparators later. To test the sorting function, we'll write a piece of test code.
SortArrayListAscendingDescendingTest. Java


package guru.springframework.blog.sortarraylist.ascendingdescending;
 import org.junit.Test;
 import java.util.ArrayList;
 import static org.junit.Assert.*;
 public class SortArrayListAscendingDescendingTest {
 <a href="http://www.jobbole.com/members/madao">@Test</a>
 public void testSortAscendingDescending() throws Exception {
 ArrayList countryList = new ArrayList<>();
 countryList.add("France");
 countryList.add("USA");
 countryList.add("India");
 countryList.add("Spain");
 countryList.add("England");
 SortArrayListAscendingDescending sortArrayList = new SortArrayListAscendingDescending(countryList);
 ArrayList unsortedArrayList = sortArrayList.getArrayList();
 System.out.println("Unsorted ArrayList: " + unsortedArrayList);
 ArrayList sortedArrayListAscending = sortArrayList.sortAscending();
 System.out.println("Sorted ArrayList in Ascending Order : " + sortedArrayListAscending);
 ArrayList sortedArrayListDescending = sortArrayList.sortDescending();
 System.out.println("Sorted ArrayList in Descending Order: " + sortedArrayListDescending);
 }
 }

In the test code above, we created an ArrayList object and added five string objects to represent the names of the five countries. Then we call the getArrayList(), sortAscending(), and sortDescending() methods, and print the ArrayList objects returned by those methods.

So far, the ArrayList elements to be sorted have been fairly simple, we just called the collections.sort () method and passed the ArrayList object to be sorted as an argument. But more often than not, you'll encounter some complex scenarios where you can sort an ArrayList.
The collections.sort () method sorts the elements of the ArrayList or Comparable elements provided by the implementation of any other List, which means that their classes need to implement the Comparable interface in the java.lang package. Just as the String class implements the Comparable interface, we can sort the ArrayList of country names. Some other standard Java classes implement the Comparable interface, including the original wrapper classes, such as Integer, Short, Double, Float, Boolean, BigInteger, BigDecimal, File, and Date classes.

Use Comparable sort ArrayList

Comparable is an interface with a single compareTo() method. A class object that implements the Comparable interface can be compared with other objects of the same type, and a class that implements the Comparable interface needs to override the compareTo() method, which accepts an object of the same type and implements the logic for comparing that object with another object passed to the method. The compareTo() method returns a comparison of type Int, representing the following:
A positive value indicates that the current object is larger than the object passed to comPareTO()
Negative values indicate that the current object is smaller than the one passed to comPareTO()
Zero means that two objects are equal
For example, the object of the JobCandidate class is stored in the ArrayList and is ready to be sorted. The JobCandidate class has three member variables: the name and gender of the string type, and the age of the integer. We want to sort the JobCandidate object preserved in the ArrayList by age. So we want the JobCandidate class to implement the Comparable interface and override the compareTo() method.
The code for the JobCandidate class is as follows:
JobCandidate. Java


package guru.springframework.blog.sortarraylist.comparable;
 public class JobCandidate implements Comparable {
 private String name;
 private String gender;
 private int age;
 public JobCandidate(String name, String gender, int age) {
 this.name = name;
 this.gender = gender;
 this.age = age;
 }
 public String getName() {
 return name;
 }
 public String getGender() {
 return gender;
 }
 public int getAge() {
 return age;
 }
 @Override
 public int compareTo(JobCandidate candidate) {
 return (this.getAge() < candidate.getAge() ? -1 :
 (this.getAge() == candidate.getAge() ? 0 : 1));
 }
 @Override
 public String toString() {
 return " Name: " + this.name + ", Gender: " + this.gender + ", age:" + this.age;
 }
 }

In the compareTo() method where the JobCandidate class was rewritten above, we implemented age-based comparison logic. I've seen a lot of programmers return "this.getage ()" as a comparison. Although using this return statement seems appealing and will not affect our example, my advice is to stay away from it. Imagine comparing integer values where one or both of them are negative. This can lead to errors that can cause your program to behave erratically and, more importantly, can be subtle and difficult to detect, especially in large enterprise applications. Next we will write an auxiliary class to sort the ArrayList object that contains the JobCandidate element for the delegate.
JobCandidateSorter. Java


package guru.springframework.blog.sortarraylist.comparable;
import java.util.ArrayList;
 import java.util.Collections;
 public class JobCandidateSorter {
 ArrayList jobCandidate = new ArrayList<>();
 public JobCandidateSorter(ArrayList jobCandidate) {
 this.jobCandidate = jobCandidate;
 }
 public ArrayList getSortedJobCandidateByAge() {
 Collections.sort(jobCandidate);
 return jobCandidate;
 }
 }

In the JobCandidateSorter class, we initialize an ArrayList object, and the delegate will instantiate the JobCandidateSorter through the constructor. Then we write getSortedJobCandidateByAge () method, in this method, we call the Collections. The sort () and pass has been initialized ArrayList parameter, finally return the ArrayList of sorted.
Next, let's write a test class to test our code.
JobCandidateSorterTest. Java


 package guru.springframework.blog.sortarraylist.comparable;
import org.junit.Test; import java.lang.reflect.Array; import java.util.ArrayList; import static org.junit.Assert.*; public class JobCandidateSorterTest { <a href="http://www.jobbole.com/members/madao">@Test</a> public void testGetSortedJobCandidateByAge() throws Exception { JobCandidate jobCandidate1 = new JobCandidate("Mark Smith", "Male", 26); JobCandidate jobCandidate2 = new JobCandidate("Sandy Hunt", "Female", 23); JobCandidate jobCandidate3 = new JobCandidate("Betty Clark", "Female", 20); JobCandidate jobCandidate4 = new JobCandidate("Andrew Styne", "Male", 24); ArrayList jobCandidateList = new ArrayList<>(); jobCandidateList.add(jobCandidate1); jobCandidateList.add(jobCandidate2); jobCandidateList.add(jobCandidate3); jobCandidateList.add(jobCandidate4); JobCandidateSorter jobCandidateSorter = new JobCandidateSorter(jobCandidateList); ArrayList sortedJobCandidate = jobCandidateSorter.getSortedJobCandidateByAge(); System.out.println("-----Sorted JobCandidate by age: Ascending-----"); for (JobCandidate jobCandidate : sortedJobCandidate) { System.out.println(jobCandidate); } } }

In the test class above, we created four JobCandidate objects and added them to the ArrayList, then passed the ArrayList to the constructor to instantiate the JobCandidateSorter class. Finally, we call getSortedJobCandidateByAge JobCandidateSorter class () method, and print out this method returns the ArrayList after sorting.

Sorting an ArrayList using Comparable is a common method. But you have to know that there are certain limits. The class of the object you want to sort must implement Comparable and override the compareTo() method. This basically means that you will only be able to compare objects based on one member variable (the age field in our example). What if you were asked to sort the JobCandidate object by name and age? Comparable is not the solution. In addition, the comparison logic is part of the class of the object to be compared, eliminating the possibility of reusability of the comparison logic. Java addresses the above comparison requirements by using the Comparator interface provided under the java.util package.

Use the Comparator to sort the ArrayList

The Comparator interface is similar to the Comparable interface and provides a single comparison method called compare(). However, unlike the Comparable compareTo() method, this compare() accepts two different objects of the same type for comparison.
We'll use the Comparator to sort the same JobCandidate class object that we used before. We will allow the JobCandidate object to be sorted by age and name by implementing the Comparatoras anonymous inner class.
Here is the code for the JobCandidate class that USES the Comparator
JobCandidate. Java


package guru.springframework.blog.sortarraylist.comparator;
 import java.util.Comparator;
 public class JobCandidate {
 private String name;
 private String gender;
 private int age;
 public JobCandidate(String name, String gender, int age) {
 this.name = name;
 this.gender = gender;
 this.age = age;
 }
 public String getName() {
 return name;
 }
 public String getGender() {
 return gender;
 }
 public int getAge() {
 return age;
 }
 public static Comparator ageComparator = new Comparator() {
 @Override
 public int compare(JobCandidate jc1, JobCandidate jc2) {
 return (jc2.getAge() < jc1.getAge() ? -1 :
 (jc2.getAge() == jc1.getAge() ? 0 : 1));
 }
 };
 public static Comparator nameComparator = new Comparator() {
 @Override
 public int compare(JobCandidate jc1, JobCandidate jc2) {
 return (int) (jc1.getName().compareTo(jc2.getName()));
 }
 };
 @Override
 public String toString() {
 return " Name: " + this.name + ", Gender: " + this.gender + ", age:" + this.age;
 }
 }

In the above class, from lines 29 to 35, we wrote an anonymous class and implemented the compare() method, sorting the JobCandidate object in descending order of age. From lines 37 to 42, we write an anonymous class and implement the compare() method, sorting JobCandidate in ascending order of name. Now let's write a class that sorts the elements of the ArrayList for the delegate.
JobCandidateSorter. Java


package guru.springframework.blog.sortarraylist.comparator;
 import java.util.ArrayList;
 import java.util.Collections;
 public class JobCandidateSorter {
 ArrayList jobCandidate = new ArrayList<>();
 public JobCandidateSorter(ArrayList jobCandidate) {
 this.jobCandidate = jobCandidate;
 }
 public ArrayList getSortedJobCandidateByAge() {
 Collections.sort(jobCandidate, JobCandidate.ageComparator);
 return jobCandidate;
 }
 public ArrayList getSortedJobCandidateByName() {
 Collections.sort(jobCandidate, JobCandidate.nameComparator);
 return jobCandidate;
 }
 }

In the class above, we wrote getSortedJobCandidateByAge () method, in this method we call within the Collections. The sort () overloaded versions, this version will be sorting the ArrayList object and to compare the Comparator object. In getSortedJobCandidateByName () method, we call again the Collections. The sort () another overloaded versions, this version is going to be ordering the ArrayList object and the name of the comparison of Comparator object.
Let's write a test class to test our code.
Let's write a test class to test our code.
JobCandidateSorterTest. Java


package guru.springframework.blog.sortarraylist.comparator;
 import guru.springframework.blog.sortarraylist.comparator.JobCandidate;
 import guru.springframework.blog.sortarraylist.comparator.JobCandidateSorter;
 import org.junit.Before;
 import org.junit.Test;
 import java.util.ArrayList;
 import static org.junit.Assert.*;
 public class JobCandidateSorterTest {
 JobCandidateSorter jobCandidateSorter;
 @Before
 public void setUp() throws Exception {
 JobCandidate jobCandidate1 = new JobCandidate("Mark Smith", "Male", 26);
 JobCandidate jobCandidate2 = new JobCandidate("Sandy Hunt", "Female", 23);
 JobCandidate jobCandidate3 = new JobCandidate("Betty Clark", "Female", 20);
 JobCandidate jobCandidate4 = new JobCandidate("Andrew Styne", "Male", 24);
 ArrayList jobCandidateList = new ArrayList<>();
 jobCandidateList.add(jobCandidate1);
 jobCandidateList.add(jobCandidate2);
 jobCandidateList.add(jobCandidate3);
 jobCandidateList.add(jobCandidate4);
 jobCandidateSorter = new JobCandidateSorter(jobCandidateList);
 }
 <a href="http://www.jobbole.com/members/madao">@Test</a>
 public void testGetSortedJobCandidateByAge() throws Exception {
 System.out.println("-----Sorted JobCandidate by age: Descending-----");
ArrayList sortedJobCandidate = jobCandidateSorter.getSortedJobCandidateByAge();
 for (JobCandidate jobCandidate : sortedJobCandidate) {
 System.out.println(jobCandidate);
 }
 }
 <a href="http://www.jobbole.com/members/madao">@Test</a>
 public void testGetSortedJobCandidateByName() throws Exception {
 System.out.println("-----Sorted JobCandidate by name: Ascending-----");
ArrayList sortedJobCandidate = jobCandidateSorter.getSortedJobCandidateByName();
 for (JobCandidate jobCandidate : sortedJobCandidate) {
 System.out.println(jobCandidate);
 }
 }
 }

In the test class we added several JobCandidate objects to the ArrayList and created a JobCandidateSorter object in the setup() method of the test unit using the Before annotation. If you are new to Junit, refer to my previous articles that included Junit comments (Junit unit test series). In testGetSortedJobCandidateByAge () test method we call getSortedJobCandidateByAge () method, and print the sorted this method returns the ArrayList. In testGetSortedJobCandidateByName () test method we call getSortedJobCandidateByName () method and also print this method returns the ArrayList.

In this article we've seen different ways to sort ArrayList. One is to use Comparable and the other is to use a Comparator. The choice of methods has always been a source of confusion for programmers. The best thing to remember is that a Comparable object can say, "I can compare myself to another object" and a Comparator can say, "I can compare two different objects." You can't say that one interface is better than another. The interface you choose depends on the functionality you need to implement.

The above is the entire content of this article, I hope to help you with your study.


Related articles: