Giao diện Java SortedMap

Trong hướng dẫn này, chúng ta sẽ tìm hiểu về giao diện Java SortedMap và các phương thức của nó.

Các SortedMapgiao diện của khuôn khổ bộ sưu tập Java cung cấp sắp xếp các phím được lưu trữ trong một bản đồ.

Nó mở rộng giao diện Bản đồ .

Lớp triển khai SortedMap

Vì SortedMaplà một giao diện nên chúng ta không thể tạo các đối tượng từ nó.

Để sử dụng các chức năng của SortedMapgiao diện, chúng ta cần sử dụng lớp TreeMaptriển khai nó.

Làm thế nào để sử dụng SortedMap?

Để sử dụng SortedMap, chúng ta phải nhập java.util.SortedMapgói trước. Sau khi chúng tôi nhập gói, đây là cách chúng tôi có thể tạo một bản đồ được sắp xếp.

// SortedMap implementation by TreeMap class
SortedMap<Key, Value> numbers = new TreeMap<>();

Chúng tôi đã tạo một bản đồ được sắp xếp được gọi là các số bằng cách sử dụng TreeMaplớp.

Đây,

  • Key – a unique identifier used to associate each element (value) in a map
  • Value – elements associated by keys in a map

Ở đây, chúng tôi không sử dụng đối số để tạo một bản đồ được sắp xếp. Do đó bản đồ sẽ được sắp xếp tự nhiên (thứ tự tăng dần).

Phương thức của Bản đồ sắp xếp

Các SortedMapgiao diện bao gồm tất cả các phương pháp của Mapgiao diện. Đó là bởi vì Maplà một giao diện siêu của SortedMap.

Bên cạnh tất cả các phương pháp đó, đây là các phương thức dành riêng cho SortedMapgiao diện.

  • comparator() – returns a comparator that can be used to order keys in a map
  • firstKey() – returns the first key of the sorted map
  • lastKey() – returns the last key of the sorted map
  • headMap(key) – returns all the entries of a map whose keys are less than the specified key
  • tailMap(key) – returns all the entries of a map whose keys are greater than or equal to the specified key
  • subMap(key1, key2) – returns all the entries of a map whose keys lies in between key1 and key2 including key1

Để tìm hiểu thêm, hãy truy cập Java SortedMap (tài liệu Java chính thức) .

Triển khai Bản đồ sắp xếp trong Lớp Sơ đồ cây

import java.util.SortedMap;
import java.util.TreeMap;

class Main {

    public static void main(String[] args) {
        // Creating SortedMap using TreeMap
        SortedMap<String, Integer> numbers = new TreeMap<>();

        // Insert elements to map
        numbers.put("Two", 2);
        numbers.put("One", 1);
        System.out.println("SortedMap: " + numbers);


        // Access the first key of the map
        System.out.println("First Key: " + numbers.firstKey());

        // Access the last key of the map
        System.out.println("Last Key: " + numbers.lastKey());

        // Remove elements from the map
        int value = numbers.remove("One");
        System.out.println("Removed Value: " + value);
    }
}

Đầu ra

SortedMap: {One=1, Two=2}
First Key: One
Last Key: Two
Removed Value: 1

Ở đây, chúng tôi hiển thị cách SortedMapgiao diện hoạt động. Nếu bạn muốn biết thêm về cách triển khai của nó, hãy truy cập Java TreeMap .









Gõ tìm kiếm nhanh...