Review Java sort list of objects by field Mới nhất

Kinh Nghiệm về Java sort list of objects by field Mới Nhất

Ban đang tìm kiếm từ khóa Java sort list of objects by field được Update vào lúc : 2022-12-14 23:42:05 . Với phương châm chia sẻ Kinh Nghiệm về trong nội dung bài viết một cách Chi Tiết Mới Nhất. Nếu sau khi Read nội dung bài viết vẫn ko hiểu thì hoàn toàn có thể lại phản hồi ở cuối bài để Admin lý giải và hướng dẫn lại nha.

How to Sort an ArrayList of Objects by Property in Java?

ArrayList in Java (equivalent to vector in C++) having a dynamic size. It can be shrinked or expanded based on size. ArrayList is a part of the collection framework and is present in java.util package.

ArrayList <E> list = new ArrayList <> ();

Approach 1:

Attention reader! Dont stop learning now. Get hold of all the important Java Foundation and Collections concepts with the Fundamentals of Java and Java Collections Course a student-friendly price and become industry ready. To complete your preparation from learning a language to DS Algo and many more, please refer Complete Interview Preparation Course.

In the below program, weve defined a CustomObject class with a String property, customProperty.
Weve also added a constructor that initializes the property, and a getter function getCustomProperty() which returns customProperty.
In the main() method, weve created an array list of custom objects list, initialized with 5 objects.
For sorting the list with the given property, we use the lists sort() method.
The sort() method takes the list to be sorted (final sorted list is also the same) and a comparator.

In our case, the comparator is a lambda which-

Code:

Java

// Java program to sort the ArrayList
// of objects by property

import java.util.*;

// Define a custom class with custom property
// It takes and stores custom objects

class CustomObject

private String customProperty;

public CustomObject(String property)

this.customProperty = property;

public String getCustomProperty()

return this.customProperty;

public class GFG

// printing sorted ArrayList objects using enchanced

// for loop

public static void print(ArrayList<CustomObject> list)

for (CustomObject obj : list)

System.out.println(obj.getCustomProperty());

// Comparison done using compareTo function

public static void sort(ArrayList<CustomObject> list)

list.sort((o1, o2)

-> o1.getCustomProperty().compareTo(

o2.getCustomProperty()));

// Adding custom objects

public static void add(ArrayList<CustomObject> list)

list.add(new CustomObject(“Z”));

list.add(new CustomObject(“A”));

list.add(new CustomObject(“B”));

list.add(new CustomObject(“X”));

list.add(new CustomObject(“Aa”));

public static void main(String[] args)

// Declare ArrayList with custom class

ArrayList<CustomObject> list = new ArrayList<>();

add(list);

sort(list);

print(list);

Output
A
Aa
B
X
Z

Approach 2: Using Comparable and comparator

When the ArrayList is of a custom object type, then in this case we use two sorting methods by either Comparator or Comparable and in this case Collections.sort() cannot be used directly as it will give error because it sorts only specific data-types and not user-defined types.

Sorting ArrayList with Comparable:

The custom object type class which is Student here will implement the Comparable class<Student>.
This will override the compareTo() method of Comparable class which takes the object of class Student as a parameter, and we need to compare the values/ attributes by which we want to sort the list and return accordingly in the compareTo() function.
Java

// Java program to sort ArrayList of
// custom object using Comparable class

import java.util.*;

class ArrayListSorting

public static void main(String args[])

ArrayList<Student> arraylist

= new ArrayList<Student>();

arraylist.add(new Student(12, “Riya”, 15));

arraylist.add(new Student(14, “Mahima”, 16));

arraylist.add(new Student(13, “Shubhi”, 15));

Collections.sort(arraylist);

for (Student str : arraylist)

System.out.println(str);

public class Student implements Comparable<Student>

private String studentname;

private int rollno;

private int studentage;

public Student(int rollno, String studentname,

int studentage)

this.rollno = rollno;

this.studentname = studentname;

this.studentage = studentage;

// getter and setter functions

public String getStudentname() return studentname;

public void setStudentname(String studentname)

this.studentname = studentname;

public int getRollno() return rollno;

public void setRollno(int rollno)

this.rollno = rollno;

public int getStudentage() return studentage;

public void setStudentage(int studentage)

this.studentage = studentage;

// overriding the compareTo method of Comparable class

@Override public int compareTo(Student comparestu)

int compareage

= ((Student)comparestu).getStudentage();

// For Ascending order

return this.studentage – compareage;

// For Descending order do like this

// return compareage-this.studentage;

@Override public String toString()

return “[ rollno=” + rollno + “, name=”

+ studentname + “, age=” + studentage + “]”;

Output
[ rollno=12, name=Riya, age=15]
[ rollno=13, name=Shubhi, age=15]
[ rollno=14, name=Mahima, age=16]

Sorting ArrayList with Comparator:

We will define another class that will implement the Comparator class of type of our custom object. For eg, in the below code, our custom class is Student so another class that we have defined will implement Comparatot<Student>.
This class will override the compare method of the Comparator class which accepts two objects of the Student class as parameters and returns the comparison value according to our requirement whether we want to sort the array in ascending or descending order and on which attribute, we want to sort the list.
Java

// Java program to sort the ArrayList
// of custom object using Comparator class

import java.util.*;

import java.util.Comparator;

public class Student

private String studentname;

private int rollno;

private int studentage;

public Student(int rollno, String studentname,

int studentage)

this.rollno = rollno;

this.studentname = studentname;

this.studentage = studentage;

// getter and setter functions

public String getStudentname() return studentname;

public void setStudentname(String studentname)

this.studentname = studentname;

public int getRollno() return rollno;

public void setRollno(int rollno)

this.rollno = rollno;

public int getStudentage() return studentage;

public void setStudentage(int studentage)

this.studentage = studentage;

public static Comparator<Student> StuNameComparator = new Comparator<Student>()

public int compare(Student s1, Student s2)

String StudentName1

= s1.getStudentname().toUpperCase();

String StudentName2

= s2.getStudentname().toUpperCase();

// ascending order

return StudentName1.compareTo(

StudentName2);

// descending order

// return

// StudentName2.compareTo(StudentName1);

;

// Comparator for sorting the list by roll no

public static Comparator<Student> StuRollno = new Comparator<Student>()

public int compare(Student s1, Student s2)

int rollno1 = s1.getRollno();

int rollno2 = s2.getRollno();

// For ascending order

return rollno1 – rollno2;

// For descending order

// rollno2-rollno1;

;

@Override public String toString()

return “[ rollno=” + rollno + “, name=”

+ studentname + “, age=” + studentage + “]”;

class Details

public static void main(String args[])

ArrayList<Student> arraylist

= new ArrayList<Student>();

arraylist.add(new Student(101, “Zues”, 26));

arraylist.add(new Student(505, “Abey”, 24));

arraylist.add(new Student(809, “Vignesh”, 32));

// Sorting based on Student Name

System.out.println(“Student Name Sorting:”);

Collections.sort(arraylist,

Student.StuNameComparator);

for (Student str : arraylist)

System.out.println(str);

// Sorting on Rollno property

System.out.println(“RollNum Sorting:”);

Collections.sort(arraylist, Student.StuRollno);

for (Student str : arraylist)

System.out.println(str);

Output
Student Name Sorting:
[ rollno=505, name=Abey, age=24]
[ rollno=809, name=Vignesh, age=32]
[ rollno=101, name=Zues, age=26]
RollNum Sorting:
[ rollno=101, name=Zues, age=26]
[ rollno=505, name=Abey, age=24]
[ rollno=809, name=Vignesh, age=32]

Article Tags :

JavaJava Programs

Java-ArrayList
Practice Tags : Java

Read Full Article

Reply
7
0
Chia sẻ

Video Java sort list of objects by field ?

Bạn vừa tìm hiểu thêm tài liệu Với Một số hướng dẫn một cách rõ ràng hơn về Clip Java sort list of objects by field tiên tiến và phát triển nhất

Share Link Tải Java sort list of objects by field miễn phí

Quý khách đang tìm một số trong những Chia Sẻ Link Cập nhật Java sort list of objects by field miễn phí.

Hỏi đáp vướng mắc về Java sort list of objects by field

Nếu Bạn sau khi đọc nội dung bài viết Java sort list of objects by field , bạn vẫn chưa hiểu thì hoàn toàn có thể lại phản hồi ở cuối bài để Ad lý giải và hướng dẫn lại nha
#Java #sort #list #objects #field

Exit mobile version