溫馨提示×

java自動排序的集合怎么寫

小億
121
2023-11-01 19:11:03
欄目: 編程語言

Java中有多種自動排序的集合類可以使用,其中最常用的是TreeSetTreeMap。

TreeSet是一個有序的集合,它根據元素的自然順序進行排序。如果希望使用自定義的順序來進行排序,可以在創建TreeSet對象時傳入一個Comparator對象作為參數。

以下是使用TreeSet進行自動排序的示例代碼:

import java.util.TreeSet;

public class TreeSetExample {
    public static void main(String[] args) {
        // 創建一個空的TreeSet對象
        TreeSet<Integer> numbers = new TreeSet<>();

        // 添加元素到集合中
        numbers.add(5);
        numbers.add(3);
        numbers.add(8);
        numbers.add(1);
        numbers.add(4);

        // 遍歷并打印集合中的元素
        for (Integer number : numbers) {
            System.out.println(number);
        }
    }
}

輸出結果為:

1
3
4
5
8

TreeMap是一個有序的鍵值對集合,它根據鍵的自然順序進行排序。如果希望使用自定義的順序來進行排序,可以在創建TreeMap對象時傳入一個Comparator對象作為參數。

以下是使用TreeMap進行自動排序的示例代碼:

import java.util.TreeMap;

public class TreeMapExample {
    public static void main(String[] args) {
        // 創建一個空的TreeMap對象
        TreeMap<Integer, String> students = new TreeMap<>();

        // 添加鍵值對到集合中
        students.put(5, "Alice");
        students.put(3, "Bob");
        students.put(8, "Charlie");
        students.put(1, "David");
        students.put(4, "Emily");

        // 遍歷并打印集合中的鍵值對
        for (Integer key : students.keySet()) {
            System.out.println(key + ": " + students.get(key));
        }
    }
}

輸出結果為:

1: David
3: Bob
4: Emily
5: Alice
8: Charlie

以上就是使用Java自動排序的集合的示例代碼,你可以根據實際需求來選擇適合的集合類。

0
亚洲午夜精品一区二区_中文无码日韩欧免_久久香蕉精品视频_欧美主播一区二区三区美女