Check Mobile App
Read now
Start a Project

How to sort ArrayList with user-defined class

Save

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.

. . .

Leave a Comment

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


Be the first to comment.

css.php

Great Product, Great Team, and Great Support Service. And if you want to add more features to the product, they can submit any idea that comes to your mind. They really care about their clients and we are really happy and honored to deal with Webkul.

Osama
Talk to Sales

Global

Live Chat
Start a Project

    Message Sent!

    If you have more details or questions, you can reply to the received confirmation email.

    Back to Home