📜  对 ArrayList 进行排序的Java程序

📅  最后修改于: 2022-05-13 01:54:22.790000             🧑  作者: Mango

对 ArrayList 进行排序的Java程序

ArrayList 是 Collection 框架中提供的类。在Java中,集合框架在Java.util 包中定义。 ArrayList 用于动态存储元素。它比数组更灵活,因为 ArrayList 中没有大小限制。 ArrayList 以无序方式存储数据。在某些情况下,我们需要以有序的方式重新排列数据。

Java中有两种类型的 ArrayList 。一个是 Wrapper 类对象的 ArrayList,另一个是用户定义对象的 ArrayList。我们将看到两种类型的 ArrayList 的排序。让我们从第一个开始。

  1. 对包装类对象的 ArrayList 进行排序。
    • 升序
    • 降序排列
  2. 对用户定义的对象的 ArrayList 进行排序。
    • 可比
    • 比较器

类型 1:对 Wrapper Class 对象的 ArrayList 进行排序

Wrapper 类对象的 ArrayList 只不过是 String、Integers 等对象的 ArrayList。ArrayList 可以按升序和降序两种方式排序。集合类提供了两种对ArrayList 进行排序的方法。 sort() 和 reverseOrder() 分别用于升序和降序。

1(A)升序

此 sort() 方法接受列表对象作为参数,它将返回按升序排序的 ArrayList。 sort() 方法的语法如下所示。

Collections.sort(objectOfArrayList);

ArrayList 中的所有元素必须相互比较,否则会抛出ClassCastException 。这里,相互比较是指列表中的所有项目都具有相同的数据类型。

ArrayList list = new ArrayList();   
list.add(132);  
list.add(321);   
list.add("India");

在上面的例子中,我们看到一个列表有三个元素,其中两个元素是 Integer 类型,一个是 String 类型。 Integer 中的两个元素可以相互比较,而String 类型的元素与另外两个元素不可比较。在这种情况下,我们可以得到一个 ClassCastException。因此,列表必须具有相同类型的元素。

让我们考虑以下示例来理解排序。

Java
// Java Program to Sort an ArrayList
 
// import java.util package
import java.util.*;
 
class GFG {
 
    // Main driver method
    public static void main(String[] args)
    {
        // Define an objects of ArrayList class
        ArrayList list = new ArrayList();
 
        // Adding elements to the ArrayList
        list.add("India");
        list.add("Pakistan");
        list.add("Srilanka");
        list.add("USA");
        list.add("Australia");
        list.add("Japan");
 
        // Printing the unsorted ArrayList
        System.out.println("Before Sorting : " + list);
 
        // Sorting ArrayList in ascending Order
        Collections.sort(list);
 
        // printing the sorted ArrayList
        System.out.println("After Sorting : " + list);
    }
}


Java
// Java Program to Sort an ArrayList
 
// Importing generic java files
import java.util.*;
 
public class GFG {
 
    // Main driver method
    public static void main(String[] args)
    {
        // Define an objects of ArrayList class
        ArrayList list = new ArrayList();
 
        // Adding elements to the ArrayList
        list.add(410);
        list.add(250);
        list.add(144);
        list.add(967);
        list.add(289);
        list.add(315);
 
        // Printing the unsorted ArrayList
        System.out.println("Before Sorting : " + list);
 
        // Sorting ArrayList in descending Order
        Collections.sort(list, Collections.reverseOrder());
 
        // Printing the sorted ArrayList
        System.out.println("After Sorting : " + list);
    }
}


Java
// Java Program to Sort an ArrayList
 
// Importing generic java files
import java.util.*;
 
// Implements comparable interface into custom class
class Car implements Comparable {
    int ModalNo;
    String name;
    int stock;
 
    // Parameterized constructor of the class
    Car(int ModalNo, String name, int stock)
    {
        this.ModalNo = ModalNo;
        this.name = name;
        this.stock = stock;
    }
 
    // Override the compareTo method
    public int compareTo(Car car)
    {
        if (stock == car.stock)
            return 0;
        else if (stock > car.stock)
            return 1;
        else
            return -1;
    }
}
 
// Main driver method
class GFG {
 
    // Main driver method
    public static void main(String[] args)
    {
        // Create the ArrayList object
        ArrayList c = new ArrayList();
        c.add(new Car(2018, "Kia", 20));
        c.add(new Car(2020, "MG", 13));
        c.add(new Car(2013, "creta", 10));
        c.add(new Car(2015, "BMW", 50));
        c.add(new Car(2017, "Audi", 45));
 
        // Call the sort function
        Collections.sort(c);
 
        // Iterate over ArrayList using for each loop
        for (Car car : c) {
 
            // Print the sorted ArrayList
            System.out.println(car.ModalNo + " " + car.name
                               + " " + car.stock);
        }
    }
}


Java
// Java Program to Sort an ArrayList
 
// Step 1: ImportingDB files
import java.util.*;
 
// Class 1: Parent Class
class Car {
    int ModalNo;
    String name;
    int stock;
 
    // Parameterized constructor
    Car(int ModalNo, String name, int stock)
    {
        this.ModalNo = ModalNo;
        this.name = name;
        this.stock = stock;
    }
}
 
// Class 2: Child class
// creates the comparator for comparing stock value
class StockComparator implements Comparator {
 
    // Function to compare
    public int compare(Car c1, Car c2)
    {
        if (c1.stock == c2.stock)
            return 0;
        else if (c1.stock > c2.stock)
            return 1;
        else
            return -1;
    }
}
 
class GFG {
 
    // Main driver method
    public static void main(String[] args)
    {
        // Create the ArrayList object
        ArrayList c = new ArrayList();
        c.add(new Car(2018, "Kia", 20));
        c.add(new Car(2020, "MG", 13));
        c.add(new Car(2013, "creta", 10));
        c.add(new Car(2015, "BMW", 50));
        c.add(new Car(2017, "Audi", 45));
 
        // Call the sort function
        Collections.sort(c, new StockComparator());
 
        // For each loop to iterate
        for (Car car : c) {
           
          // Print the sorted ArrayList
            System.out.println(car.stock + " " + car.name
                               + " " + car.ModalNo);
        }
    }
}


输出:

Before Sorting : [India, Pakistan, Srilanka, USA, Australia, Japan]
After Sorting : [Australia, India, Japan, Pakistan, Srilanka, USA]

1(B) 降序

要按降序对 ArrayList 进行排序,我们使用reverseOrder()方法作为 sort() 方法的参数。我们不能直接调用 reverseOrder() 方法。该方法有两个参数,一个是 ArrayList 的对象,第二个参数是 Collections.reversOrder() 方法。此方法将按降序返回 ArrayList。类似于 sort() 方法 ArrayList 必须可以相互比较,否则它会抛出ClassCastException

Collections.sort(objectOfArrayList, Collections.reverseOrder());

在这里,此方法首先按升序对项目进行排序,然后将排序项目的顺序颠倒。

Java

// Java Program to Sort an ArrayList
 
// Importing generic java files
import java.util.*;
 
public class GFG {
 
    // Main driver method
    public static void main(String[] args)
    {
        // Define an objects of ArrayList class
        ArrayList list = new ArrayList();
 
        // Adding elements to the ArrayList
        list.add(410);
        list.add(250);
        list.add(144);
        list.add(967);
        list.add(289);
        list.add(315);
 
        // Printing the unsorted ArrayList
        System.out.println("Before Sorting : " + list);
 
        // Sorting ArrayList in descending Order
        Collections.sort(list, Collections.reverseOrder());
 
        // Printing the sorted ArrayList
        System.out.println("After Sorting : " + list);
    }
}

输出:

Before Sorting : [410, 250, 144, 967, 289, 315]
After Sorting : [967, 410, 315, 289, 250, 144]

2. 对用户自定义对象的 ArrayList 进行排序

用户定义对象的 ArrayList 只不过是自定义对象的 ArrayL.ist。在Java中,有两个接口可用于对集合元素进行排序。比较器和比较器。

2(A) 可比

Comparable 提供单一排序序列。如果我们使用 Comparable 它将影响原始类。 Comparable 接口提供compareTo() 对元素进行排序的方法。在Java中,可比较由Java.lang 包提供。我们可以通过调用Collections.sort(List) 方法对 ArrayList 进行排序。

示例:根据库存汽车的数量进行排序。

Java

// Java Program to Sort an ArrayList
 
// Importing generic java files
import java.util.*;
 
// Implements comparable interface into custom class
class Car implements Comparable {
    int ModalNo;
    String name;
    int stock;
 
    // Parameterized constructor of the class
    Car(int ModalNo, String name, int stock)
    {
        this.ModalNo = ModalNo;
        this.name = name;
        this.stock = stock;
    }
 
    // Override the compareTo method
    public int compareTo(Car car)
    {
        if (stock == car.stock)
            return 0;
        else if (stock > car.stock)
            return 1;
        else
            return -1;
    }
}
 
// Main driver method
class GFG {
 
    // Main driver method
    public static void main(String[] args)
    {
        // Create the ArrayList object
        ArrayList c = new ArrayList();
        c.add(new Car(2018, "Kia", 20));
        c.add(new Car(2020, "MG", 13));
        c.add(new Car(2013, "creta", 10));
        c.add(new Car(2015, "BMW", 50));
        c.add(new Car(2017, "Audi", 45));
 
        // Call the sort function
        Collections.sort(c);
 
        // Iterate over ArrayList using for each loop
        for (Car car : c) {
 
            // Print the sorted ArrayList
            System.out.println(car.ModalNo + " " + car.name
                               + " " + car.stock);
        }
    }
}

输出:

2013 creta 10
2020 MG 13
2018 Kia 20
2017 Audi 45
2015 BMW 50

2(B) 比较器

比较器提供多种排序序列。比较器不会影响原始类。 Comparator 提供了compare()方法来对元素进行排序。在Java中,可比较由Java.util 包提供。我们可以通过调用 Collections.sort(List, Comparator) 方法对 ArrayList 进行排序。让我们举一个例子。

Java

// Java Program to Sort an ArrayList
 
// Step 1: ImportingDB files
import java.util.*;
 
// Class 1: Parent Class
class Car {
    int ModalNo;
    String name;
    int stock;
 
    // Parameterized constructor
    Car(int ModalNo, String name, int stock)
    {
        this.ModalNo = ModalNo;
        this.name = name;
        this.stock = stock;
    }
}
 
// Class 2: Child class
// creates the comparator for comparing stock value
class StockComparator implements Comparator {
 
    // Function to compare
    public int compare(Car c1, Car c2)
    {
        if (c1.stock == c2.stock)
            return 0;
        else if (c1.stock > c2.stock)
            return 1;
        else
            return -1;
    }
}
 
class GFG {
 
    // Main driver method
    public static void main(String[] args)
    {
        // Create the ArrayList object
        ArrayList c = new ArrayList();
        c.add(new Car(2018, "Kia", 20));
        c.add(new Car(2020, "MG", 13));
        c.add(new Car(2013, "creta", 10));
        c.add(new Car(2015, "BMW", 50));
        c.add(new Car(2017, "Audi", 45));
 
        // Call the sort function
        Collections.sort(c, new StockComparator());
 
        // For each loop to iterate
        for (Car car : c) {
           
          // Print the sorted ArrayList
            System.out.println(car.stock + " " + car.name
                               + " " + car.ModalNo);
        }
    }
}

输出:

10 creta 2013
13 MG 2020
20 Kia 2018
45 Audi 2017
50 BMW 2015