Native Shopify Mobile App with 20 new features
Kickstart your hyperlocal marketplace in Corona pandemic with a starter guide
Android App Development
iOS App Development
Cross Platform App Development
Hire on-demand project developers and turn your idea into working reality.
Big thanks to Webkul and his team for helping get Opencart 126.96.36.199 release ready!
Owner and Founder. Opencart
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.
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.
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.
To sort the ArrayList According to var2 (int) of the example class.
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.
Your email address will not be published. Required fields are marked*
Save my name email and website in this browser for the next time I comment.
Be the first to comment.
Enquiry or Requirement
If you have more details or questions, you can reply to the received confirmation email.