Updated 29 September 2017
Suppose you have a user-defined class (Model) which contains some variables and their getters and setters and you have an ArrayList of that class. If you are looking to sort this ArrayList according to a particular variable of the class then this blog is just for you. We will learn about sorting an ArrayList (Ascending or Descending order) with a particular variable of the class it could be either a String or an int.
Let us look at our example class.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 |
public class Example { private String var1; private int var2; public Student(String var1, int var2) { this.var1 = var1; this.var2 = var2; } public String getVar1() { return var1; } public void setVar1(String var1) { this.var1 = var1; } public int getVar2() { return var2; } public void setVar2(int var2) { this.var2 = var2; } } |
In the above class as we can see we have two variables var1 of String type and var2 of int type, one constructor which will initialize these variables and getter and setter methods to modify and get the values of these variables.
For sorting the ArrayList we will be using the comparator. Java Comparator interface is used to order the objects of a user-defined class.
Let us create an ArrayList of our Example class and we will sort it according to our needs.
1 2 3 4 5 6 |
public void ArrayList<Example> exampleArrayList { ArrayList<Example> arraylist = new ArrayList<Example>(); arraylist.add(new Example(valueString1, valueInt1)); arraylist.add(new Example(valueString2, valueInt2)); arraylist.add(new Example(valueString3, valueInt3)); } |
Now we will use the sort method of Collection class to sort the ArrayList and as a parameter, we will provide the ArrayList and a Comparator.
Below is an example of the comparator which will sort the array according to the var1 (String) of the Example class.
1 2 3 4 5 6 7 8 9 10 11 |
Collections.sort(your_arraylist, new Comparator<Example>() { @Override public int compare(Example example1, Example example2) { //For Ascending Order return example1.getVar1().compareTo(example2.getVar1()); //For Descending Order //return example2.getVar1().compareTo(example1.getVar1()); } }); |
To sort the ArrayList According to var2 (int) of the example class.
1 2 3 4 5 6 7 8 9 10 11 |
Collections.sort(your_arraylist, new Comparator<Example>() { @Override public int compare(Example example1, Example example2) { //For Ascending Order return example1.getVar2() - example2.getVar2(); //For Descending Order //return example2.getVar2() - example1.getVar2(); } }); |
Just by using a simple comparator you can sort the ArrayList without any issues. This is very easy and fast way.
Thank you very much. This is Vedesh Kumar signing off.
If you have more details or questions, you can reply to the received confirmation email.
Back to Home
Be the first to comment.