如何在Java中按属性对对象的 ArrayList 进行排序?
Java中的ArrayList (相当于 C++ 中的向量)具有动态大小。它可以根据大小缩小或扩展。 ArrayList 是集合框架的一部分,存在于Java.util 包中。
ArrayList list = new ArrayList <> ();
方法一:
- 在下面的程序中,我们定义了一个带有 String 属性customProperty的 CustomObject 类。
- 我们还添加了一个初始化属性的构造函数,以及一个返回customProperty的 getter函数getCustomProperty() 。
- 在main()方法中,我们创建了一个自定义对象列表的数组列表,初始化为 5 个对象。
- 为了对具有给定属性的列表进行排序,我们使用list的sort()方法。
- sort() 方法将要排序的列表(最终排序的列表也一样)和一个 比较器。
在我们的例子中,比较器是一个 lambda,它-
- 从列表o1和 o2 中取出两个对象,
- 使用compareTo()方法比较两个对象的customProperty ,
- 最后,如果 o1 的属性大于 o2 的属性,则返回正数,如果 o1 的属性小于 o2 的属性,则返回负数,如果它们相等,则返回零。
- 在此基础上,列表根据最小属性到最大属性进行排序并存储回列表。
代码:
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 list)
{
for (CustomObject obj : list) {
System.out.println(obj.getCustomProperty());
}
}
// Comparison done using compareTo function
public static void sort(ArrayList list)
{
list.sort((o1, o2)
-> o1.getCustomProperty().compareTo(
o2.getCustomProperty()));
}
// Adding custom objects
public static void add(ArrayList 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 list = new ArrayList<>();
add(list);
sort(list);
print(list);
}
}
Java
// Java program to sort ArrayList of
// custom object using Comparable class
import java.util.*;
class ArrayListSorting {
public static void main(String args[])
{
ArrayList arraylist
= new ArrayList();
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 {
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 + "]";
}
}
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 StuNameComparator = new Comparator() {
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 StuRollno = new Comparator() {
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 arraylist
= new ArrayList();
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);
}
}
}
输出
A
Aa
B
X
Z
方法 2:使用 Comparable 和比较器
当 ArrayList 是自定义对象类型时,在这种情况下,我们通过 Comparator 或 Comparable 使用两种排序方法,在这种情况下,不能直接使用 Collections.sort() 因为它会出错,因为它只对特定数据类型进行排序而不是用户定义的类型。
使用 Comparable 对 ArrayList 进行排序:
- 此处为 Student 的自定义对象类型类将实现 Comparable class
。 - 这将覆盖 Comparable 类的 compareTo() 方法,该方法将类 Student 的对象作为参数,我们需要比较我们想要对列表进行排序的值/属性,并在 compareTo()函数中相应地返回。
Java
// Java program to sort ArrayList of
// custom object using Comparable class
import java.util.*;
class ArrayListSorting {
public static void main(String args[])
{
ArrayList arraylist
= new ArrayList();
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 {
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 + "]";
}
}
输出
[ rollno=12, name=Riya, age=15]
[ rollno=13, name=Shubhi, age=15]
[ rollno=14, name=Mahima, age=16]
使用比较器对 ArrayList 进行排序:
- 我们将定义另一个类,该类将实现自定义对象类型的 Comparator 类。例如,在下面的代码中,我们的自定义类是 Student,因此我们定义的另一个类将实现 Comparatot
。 - 该类将覆盖 Comparator 类的 compare 方法,该类接受 Student 类的两个对象作为参数,并根据我们的要求返回比较值,无论我们是要按升序还是降序对数组进行排序,以及我们要对哪个属性进行排序对列表进行排序。
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 StuNameComparator = new Comparator() {
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 StuRollno = new Comparator() {
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 arraylist
= new ArrayList();
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);
}
}
}
输出
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]