使用Java中的比较器按降序对 ArrayList 进行排序
Comparator 是一个接口,用于以排序的方式重新排列 ArrayList。比较器用于对用户定义的对象的 ArrayList 进行排序。在Java中,在Java.util 包中提供了一个 Comparator。在多个变量的基础上使用Comparator对ArrayList进行排序,或者干脆实现Comparator而不影响原来的User-defined类。要使用 Comparator 对 ArrayList 进行排序,请覆盖比较器接口提供的 compare() 方法。
以这样一种方式覆盖compare() 方法,它将按降序而不是升序对 ArrayList 重新排序。仅在比较部分更改为降序。查看两者 compare()函数之间的区别。
Ascending Order
public int compare(Item i1, Item i2)
{
if (i1.Property== i2.Property)
return 0;
else if (s1.Property > s2.Property)
return 1;
else
return -1;
}
Descending Order
public int compare(Item i1, Item i2)
{
if (i1.Property== i2.Property)
return 0;
else if (s1.Property < s2.Property)
return 1;
else
return -1;
}
如果需要根据名称等字符串类型的变量对 ArrayList 重新排序,请重写 compare()函数,如下所示。
Ascending Order
public int compare(Shop s1, Shop s2)
{
return s1.name.compareTo(s2.name);
}
Descending Order
public int compare(Shop s1, Shop s2)
{
return s2.name.compareTo(s1.name);
}
例子:
Java
// Java Program to sort the ArrayList
// in descending order using comparator
import java.util.*;
// create the Laptop class
class Laptop {
int ModalNo;
String name;
int ram;
Laptop(int ModalNo, String name, int ram)
{
this.ModalNo = ModalNo;
this.name = name;
this.ram = ram;
}
}
// creates the comparator for comparing RAM
class RamComparator implements Comparator {
// override the compare() method
public int compare(Laptop l1, Laptop l2)
{
if (l1.ram == l2.ram) {
return 0;
}
else if (l1.ram < l2.ram) {
return 1;
}
else {
return -1;
}
}
}
class GFG {
public static void main(String[] args)
{
// create the ArrayList object
ArrayList l = new ArrayList();
l.add(new Laptop(322, "Dell", 2));
l.add(new Laptop(342, "Asus", 8));
l.add(new Laptop(821, "HP", 16));
l.add(new Laptop(251, "Lenovo", 6));
l.add(new Laptop(572, "Acer", 4));
System.out.println("before sorting");
System.out.println("Ram"
+ " "
+ "Name"
+ " "
+ "ModalNo");
for (Laptop laptop : l) {
System.out.println(laptop.ram + " "
+ laptop.name + " "
+ laptop.ModalNo);
}
System.out.println();
System.out.println("After sorting(sorted by Ram)");
System.out.println("Ram"
+ " "
+ "Name"
+ " "
+ "ModalNo");
// call the sort function
Collections.sort(l, new RamComparator());
for (Laptop laptop : l) {
System.out.println(laptop.ram + " "
+ laptop.name + " "
+ laptop.ModalNo);
}
}
}
输出
before sorting
Ram Name ModalNo
2 Dell 322
8 Asus 342
16 HP 821
6 Lenovo 251
4 Acer 572
After sorting(sorted by Ram)
Ram Name ModalNo
16 HP 821
8 Asus 342
6 Lenovo 251
4 Acer 572
2 Dell 322