Trong hướng dẫn này, chúng ta sẽ tìm hiểu về lớp Java TreeMap và các hoạt động của nó với sự trợ giúp của các ví dụ.
Các TreeMap
lớp học của khuôn khổ bộ sưu tập Java cung cấp việc thực hiện cây cấu trúc dữ liệu.
Nó thực hiện giao diện NavigableMap .
Tạo sơ đồ cây
Để tạo một TreeMap
, java.util.TreeMap
trước tiên chúng ta phải nhập gói. Sau khi chúng tôi nhập gói, đây là cách chúng tôi có thể tạo một TreeMap
trong Java.
TreeMap<Key, Value> numbers = new TreeMap<>();
Trong đoạn mã trên, chúng tôi đã tạo một sốTreeMap
được đặt tên mà không có bất kỳ đối số nào. Trong trường hợp này, các phần tử trong được sắp xếp tự nhiên (thứ tự tăng dần).TreeMap
Tuy nhiên, chúng ta có thể tùy chỉnh việc sắp xếp các phần tử bằng cách sử dụng Comparator
giao diện. Chúng ta sẽ tìm hiểu về nó ở phần sau trong hướng dẫn này.
Đây,
- Key – a unique identifier used to associate each element (value) in a map
- Value – elements associated by keys in a map
Các phương thức của TreeMap
Các TreeMap
lớp học cung cấp phương pháp khác nhau mà cho phép chúng tôi thực hiện các hoạt động trên bản đồ.
Chèn các phần tử vào Sơ đồ cây
put()
– inserts the specified key/value mapping (entry) to the mapputAll()
– inserts all the entries from specified map to this mapputIfAbsent()
– inserts the specified key/value mapping to the map if the specified key is not present in the map
Ví dụ,
import java.util.TreeMap;
class Main {
public static void main(String[] args) {
// Creating TreeMap of even numbers
TreeMap<String, Integer> evenNumbers = new TreeMap<>();
// Using put()
evenNumbers.put("Two", 2);
evenNumbers.put("Four", 4);
// Using putIfAbsent()
evenNumbers.putIfAbsent("Six", 6);
System.out.println("TreeMap of even numbers: " + evenNumbers);
//Creating TreeMap of numbers
TreeMap<String, Integer> numbers = new TreeMap<>();
numbers.put("One", 1);
// Using putAll()
numbers.putAll(evenNumbers);
System.out.println("TreeMap of numbers: " + numbers);
}
}
Đầu ra
TreeMap of even numbers: {Four=4, Six=6, Two=2} TreeMap of numbers: {Four=4, One=1, Six=6, Two=2}
Truy cập phần tử bản đồ cây
1. Sử dụng entrySet (), keySet () và các giá trị ()
entrySet()
– returns a set of all the key/values mapping (entry) of a treemapkeySet()
– returns a set of all the keys of a tree mapvalues()
– returns a set of all the maps of a tree map
Ví dụ,
import java.util.TreeMap;
class Main {
public static void main(String[] args) {
TreeMap<String, Integer> numbers = new TreeMap<>();
numbers.put("One", 1);
numbers.put("Two", 2);
numbers.put("Three", 3);
System.out.println("TreeMap: " + numbers);
// Using entrySet()
System.out.println("Key/Value mappings: " + numbers.entrySet());
// Using keySet()
System.out.println("Keys: " + numbers.keySet());
// Using values()
System.out.println("Values: " + numbers.values());
}
}
Đầu ra
TreeMap: {One=1, Three=3, Two=2} Key/Value mappings: [One=1, Three=3, Two=2] Keys: [One, Three, Two] Values: [1, 3, 2]
2. Sử dụng get () và getOrDefault ()
get()
– Returns the value associated with the specified key. Returns null if the key is not found.getOrDefault()
– Returns the value associated with the specified key. Returns the specified default value if the key is not found.
Ví dụ,
import java.util.TreeMap;
class Main {
public static void main(String[] args) {
TreeMap<String, Integer> numbers = new TreeMap<>();
numbers.put("One", 1);
numbers.put("Two", 2);
numbers.put("Three", 3);
System.out.println("TreeMap: " + numbers);
// Using get()
int value1 = numbers.get("Three");
System.out.println("Using get(): " + value1);
// Using getOrDefault()
int value2 = numbers.getOrDefault("Five", 5);
System.out.println("Using getOrDefault(): " + value2);
}
}
Đầu ra
TreeMap: {One=1, Three=3, Two=2} Using get(): 3 Using getOrDefault(): 5
Ở đây, getOrDefault()
phương pháp không tìm thấy chìa khóa Năm . Do đó, nó trả về giá trị mặc định được chỉ định 5 .
Xóa các phần tử TeeMap
remove(key)
– returns and removes the entry associated with the specified key from a TreeMapremove(key, value)
– removes the entry from the map only if the specified key is associated with the specified value and returns a boolean value
Ví dụ,
import java.util.TreeMap;
class Main {
public static void main(String[] args) {
TreeMap<String, Integer> numbers = new TreeMap<>();
numbers.put("One", 1);
numbers.put("Two", 2);
numbers.put("Three", 3);
System.out.println("TreeMap: " + numbers);
// remove method with single parameter
int value = numbers.remove("Two");
System.out.println("Removed value: " + value);
// remove method with two parameters
boolean result = numbers.remove("Three", 3);
System.out.println("Is the entry {Three=3} removed? " + result);
System.out.println("Updated TreeMap: " + numbers);
}
}
Đầu ra
TreeMap: {One=1, Three=3, Two=2} Removed value = 2 Is the entry {Three=3} removed? True Updated TreeMap: {One=1}
Thay thế các phần tử TreeMap
replace(key, value)
– replaces the value mapped by the specified key with the new valuereplace(key, old, new)
– replaces the old value with the new value only if the old value is already associated with the specified keyreplaceAll(function)
– replaces each value of the map with the result of the specified function
Ví dụ,
import java.util.TreeMap;
class Main {
public static void main(String[] args) {
TreeMap<String, Integer> numbers = new TreeMap<>();
numbers.put("First", 1);
numbers.put("Second", 2);
numbers.put("Third", 3);
System.out.println("Original TreeMap: " + numbers);
// Using replace()
numbers.replace("Second", 22);
numbers.replace("Third", 3, 33);
System.out.println("TreeMap using replace: " + numbers);
// Using replaceAll()
numbers.replaceAll((key, oldValue) -> oldValue + 2);
System.out.println("TreeMap using replaceAll: " + numbers);
}
}
Đầu ra
Original TreeMap: {First=1, Second=2, Third=3} TreeMap using replace(): {First=1, Second=22, Third=33} TreeMap using replaceAll(): {First=3, Second=24, Third=35}
Trong chương trình trên, hãy chú ý câu lệnh
numbers.replaceAll((key, oldValue) -> oldValue + 2);
Ở đây, chúng ta đã chuyển một biểu thức lambda làm đối số.
Các replaceAll()
phương pháp truy cập tất cả các mục của bản đồ. Sau đó, nó thay thế tất cả các phần tử bằng các giá trị mới (được trả về từ biểu thức lambda).
Phương pháp điều hướng
Kể từ khi TreeMap
lớp triển khai NavigableMap
, nó cung cấp các phương thức khác nhau để điều hướng qua các phần tử của bản đồ dạng cây.
1. Phương pháp đầu tiên và cuối cùng
firstKey()
– returns the first key of the mapfirstEntry()
– returns the key/value mapping of the first key of the maplastKey()
– returns the last key of the maplastEntry()
– returns the key/value mapping of the last key of the map
Ví dụ,
import java.util.TreeMap;
class Main {
public static void main(String[] args) {
TreeMap<String, Integer> numbers = new TreeMap<>();
numbers.put("First", 1);
numbers.put("Second", 2);
numbers.put("Third", 3);
System.out.println("TreeMap: " + numbers);
// Using the firstKey() method
String firstKey = numbers.firstKey();
System.out.println("First Key: " + firstKey);
// Using the lastKey() method
String lastKey = numbers.lastKey();
System.out.println("Last Key: " + lastKey);
// Using firstEntry() method
System.out.println("First Entry: " + numbers.firstEntry());
// Using the lastEntry() method
System.out.println("Last Entry: " + numbers.lastEntry());
}
}
Đầu ra
TreeMap: {First=1, Second=2, Third=3} First Key: First Last Key: Third First Entry: First=1 Last Entry: Third=3
2. Phương pháp trần, sàn, cao hơn và thấp hơn
- higherKey() – Returns the lowest key among those keys that are greater than the specified key.
- higherEntry() – Returns an entry associated with a key that is lowest among all those keys greater than the specified key.
- lowerKey() – Returns the greatest key among all those keys that are less than the specified key.
- lowerEntry() – Returns an entry associated with a key that is greatest among all those keys that are less than the specified key.
- ceilingKey() – Returns the lowest key among those keys that are greater than the specified key. If the key passed as an argument is present in the map, it returns that key.
- ceilingEntry() – Returns an entry associated with a key that is lowest among those keys that are greater than the specified key. It an entry associated with the key passed an argument is present in the map, it returns the entry associated with that key.
- floorKey() – Returns the greatest key among those keys that are less than the specified key. If the key passed as an argument is present, it returns that key.
- floorEntry() – Returns an entry associated with a key that is greatest among those keys that are less than the specified key. If the key passed as argument is present, it returns that key.
Ví dụ,
import java.util.TreeMap;
class Main {
public static void main(String[] args) {
TreeMap<String, Integer> numbers = new TreeMap<>();
numbers.put("First", 1);
numbers.put("Second", 5);
numbers.put("Third", 4);
numbers.put("Fourth", 6);
System.out.println("TreeMap: " + numbers);
// Using higher()
System.out.println("Using higherKey(): " + numbers.higherKey("Fourth"));
System.out.println("Using higherEntry(): " + numbers.higherEntry("Fourth"));
// Using lower()
System.out.println("\nUsing lowerKey(): " + numbers.lowerKey("Fourth"));
System.out.println("Using lowerEntry(): " + numbers.lowerEntry("Fourth"));
// Using ceiling()
System.out.println("\nUsing ceilingKey(): " + numbers.ceilingKey("Fourth"));
System.out.println("Using ceilingEntry(): " + numbers.ceilingEntry("Fourth"));
// Using floor()
System.out.println("\nUsing floorKey(): " + numbers.floorKey("Fourth"));
System.out.println("Using floorEntry(): " + numbers.floorEntry("Fourth"));
}
}
Đầu ra
TreeMap: {First=1, Fourth=6, Second=5, Third=4} Using higherKey(): Second Using higherEntry(): Second=5 Using lowerKey(): First Using lowerEntry(): First=1 Using ceilingKey(): Fourth Using ceilingEntry(): Fourth=6 Using floorkey(): Fourth Using floorEntry(): Fourth=6
3. Phương thức thăm dò ý kiến () và PokeLastEntry ()
pollFirstEntry()
– returns and removes the entry associated with the first key of the mappollLastEntry()
– returns and removes the entry associated with the last key of the map
Ví dụ,
import java.util.TreeMap;
class Main {
public static void main(String[] args) {
TreeMap<String, Integer> numbers = new TreeMap<>();
numbers.put("First", 1);
numbers.put("Second", 2);
numbers.put("Third", 3);
System.out.println("TreeMap: " + numbers);
//Using the pollFirstEntry() method
System.out.println("Using pollFirstEntry(): " + numbers.pollFirstEntry());
// Using the pollLastEntry() method
System.out.println("Using pollLastEntry(): " + numbers.pollLastEntry());
System.out.println("Updated TreeMap: " + numbers);
}
}
Đầu ra
TreeMap: {First=1, Second=2, Third=3} Using pollFirstEntry(): First=1 Using pollLastEntry(): Third=3 Updated TreeMap: {Second=2}
4. Phương thức headMap (), tailMap () và subMap ()
headMap (key, booleanValue)
Các headMap()
phương pháp trả về tất cả các cặp khóa / giá trị của một biểu đồ dạng cây trước khi quy định quan trọng (được thông qua như là một cuộc tranh cãi).
Các booleanValue tham số là tùy chọn. Giá trị mặc định của nó là false
.
Nếu true
được truyền dưới dạng booleanValue , phương thức này cũng bao gồm cặp khóa / giá trị của cặp giá trị key
được truyền dưới dạng đối số.
Ví dụ,
import java.util.TreeMap;
class Main {
public static void main(String[] args) {
TreeMap<String, Integer> numbers = new TreeMap<>();
numbers.put("First", 1);
numbers.put("Second", 2);
numbers.put("Third", 3);
numbers.put("Fourth", 4);
System.out.println("TreeMap: " + numbers);
System.out.println("\nUsing headMap() Method:");
// Using headMap() with default booleanValue
System.out.println("Without boolean value: " + numbers.headMap("Fourth"));
// Using headMap() with specified booleanValue
System.out.println("With boolean value: " + numbers.headMap("Fourth", true));
}
}
Đầu ra
TreeMap: {First=1, Fourth=4, Second=2, Third=3} Using headMap() Method: Without boolean value: {First=1} With boolean value: {First=1, Fourth=4}
tailMap (key, booleanValue)
Các tailMap()
trở về phương pháp tất cả các cặp khóa / giá trị của một biểu đồ dạng cây bắt đầu từ quy định quan trọng (được thông qua như là một cuộc tranh cãi).
Các booleanValue là một tham số tùy chọn. Giá trị mặc định của nó là true
.
Nếu false
được truyền dưới dạng booleanValue , phương thức này không bao gồm cặp khóa / giá trị của được chỉ định key
.
Ví dụ,
import java.util.TreeMap;
class Main {
public static void main(String[] args) {
TreeMap<String, Integer> numbers = new TreeMap<>();
numbers.put("First", 1);
numbers.put("Second", 2);
numbers.put("Third", 3);
numbers.put("Fourth", 4);
System.out.println("TreeMap: " + numbers);
System.out.println("\nUsing tailMap() Method:");
// Using tailMap() with default booleanValue
System.out.println("Without boolean value: " + numbers.tailMap("Second"));
// Using tailMap() with specified booleanValue
System.out.println("With boolean value: " + numbers.tailMap("Second", false));
}
}
Đầu ra
TreeMap: {First=1, Fourth=4, Second=2, Third=3} Using tailMap() Method: Without boolean value: {Second=2, Third=3} With boolean value: {Third=3}
subMap (k1, bV1, k2, bV2)
Các subMap()
phương pháp trả về tất cả các mục có liên quan với các phím giữa k1 và k2 bao gồm sự xâm nhập của k1 .
Các BV1 và bV2 là tùy chọn thông số boolean. Giá trị mặc định của bV1 là true
và giá trị mặc định của bV2 là false
.
Nếu false
được chuyển dưới dạng bV1 , phương thức trả về tất cả các mục nhập được liên kết với các khóa giữa k1 và k2 mà không bao gồm mục nhập của k1 .
Nếu true
được chuyển dưới dạng bV2 , phương thức trả về tất cả các mục nhập được liên kết với các khóa giữa k1 và k2 bao gồm cả mục nhập của k2 .
Ví dụ,
import java.util.TreeMap;
class Main {
public static void main(String[] args) {
TreeMap<String, Integer> numbers = new TreeMap<>();
numbers.put("First", 1);
numbers.put("Second", 2);
numbers.put("Third", 3);
numbers.put("Fourth", 4);
System.out.println("TreeMap: " + numbers);
System.out.println("\nUsing subMap() Method:");
// Using subMap() with default booleanValue
System.out.println("Without boolean value: " + numbers.subMap("Fourth", "Third"));
// Using subMap() with specified booleanValue
System.out.println("With boolean value: " + numbers.subMap("Fourth", false, "Third", true));
}
}
Đầu ra
TreeMap: {First=1, Fourth=2, Second=2, Third=3} Using subMap() Method: Without boolean value: {Fourth=4, Second=2} With boolean value: {Second=2, Third=3}
Các phương pháp khác của TreeMap
Method | Decfscription |
---|---|
clone() | Creates a copy of the TreeMap |
containsKey() | Searches the TreeMap for the specified key and returns a boolean result |
containsValue() | Searches the TreeMap for the specified value and returns a boolean result |
size() | Returns the size of the TreeMap |
clear() | Removes all the entries from the TreeMap |
Bộ so sánh bản đồ cây
Trong tất cả các ví dụ ở trên, các phần tử của bản đồ dạng cây được sắp xếp tự nhiên (theo thứ tự tăng dần). Tuy nhiên, chúng tôi cũng có thể tùy chỉnh thứ tự các phím.
Đối với điều này, chúng tôi cần tạo lớp so sánh của riêng mình dựa trên các khóa trong một biểu đồ cây được sắp xếp. Ví dụ,
import java.util.TreeMap;
import java.util.Comparator;
class Main {
public static void main(String[] args) {
// Creating a treemap with a customized comparator
TreeMap<String, Integer> numbers = new TreeMap<>(new CustomComparator());
numbers.put("First", 1);
numbers.put("Second", 2);
numbers.put("Third", 3);
numbers.put("Fourth", 4);
System.out.println("TreeMap: " + numbers);
}
// Creating a comparator class
public static class CustomComparator implements Comparator<String> {
@Override
public int compare(String number1, String number2) {
int value = number1.compareTo(number2);
// elements are sorted in reverse order
if (value > 0) {
return -1;
}
else if (value < 0) {
return 1;
}
else {
return 0;
}
}
}
}
Đầu ra
TreeMap: {Third=3, Second=2, Fourth=4, First=1}
Trong ví dụ trên, chúng ta đã tạo một treemap truyền lớp CustomComparator làm đối số.
Lớp CustomComparator thực hiện Comparator
giao diện.
Sau đó, chúng tôi ghi đè compare()
phương thức để sắp xếp các phần tử theo thứ tự ngược lại.
Để tìm hiểu thêm, hãy truy cập Trình so sánh Java (tài liệu Java chính thức) .