Trong hướng dẫn này, chúng ta sẽ tìm hiểu về lớp Java LinkedHashMap và các hoạt động của nó với sự trợ giúp của các ví dụ.
Các LinkedHashMap
lớp học của khuôn khổ bộ sưu tập Java cung cấp các bảng băm và liên kết thực hiện danh sách các giao diện Map .
Các LinkedHashMap
giao diện mở rộng HashMap lớp để lưu trữ các mục của nó trong một bảng băm. Nó duy trì nội bộ một danh sách được liên kết kép giữa tất cả các mục nhập của nó để sắp xếp các mục nhập của nó.
Tạo một LinkedHashMap
Để tạo một bản đồ băm được liên kết, java.util.LinkedHashMap
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 các bản đồ băm được liên kết trong Java.
// LinkedHashMap with initial capacity 8 and load factor 0.6
LinkedHashMap<Key, Value> numbers = new LinkedHashMap<>(8, 0.6f);
Trong đoạn mã trên, chúng tôi đã tạo một bản đồ băm được liên kết có tên là các số .
Đây,
- Key – a unique identifier used to associate each element (value) in a map
- Value – elements associated by the keys in a map
Chú ý phần new LinkedHashMap<>(8, 0.6)
. Ở đây, tham số đầu tiên là dung lượng và tham số thứ hai là loadFactor .
- capacity – The capacity of this linked hashmap is 8. Meaning, it can store 8 entries.
- loadFactor – The load factor of this linked hashmap is 0.6. This means, whenever our hash map is filled by 60%, the entries are moved to a new hash table of double the size of the original hash table.
Công suất mặc định và hệ số tải
Có thể tạo một bản đồ băm được liên kết mà không cần xác định dung lượng và hệ số tải của nó. Ví dụ,
//LinkedHashMap with default capacity and load factor
LinkedHashMap<Key, Value> numbers1 = new LinkedHashMap<>();
Theo mặc định,
- the capacity of the linked hashmap will be 16
- the load factor will be 0.75
Lưu ý : LinkedHashMap
Lớp cũng cho phép chúng ta xác định thứ tự của các mục nhập của nó. Ví dụ
// LinkedHashMap with specified order
LinkedHashMap<Key, Value> numbers2 = new LinkedHashMap<>(capacity, loadFactor, accessOrder);
Ở đây, accessOrder là một giá trị boolean. Giá trị mặc định của nó là false
. Trong trường hợp này, các mục nhập trong bản đồ băm được liên kết được sắp xếp dựa trên thứ tự chèn của chúng.
Tuy nhiên, nếu true
được chuyển dưới dạng accessOrder , các mục nhập trong bản đồ băm được liên kết sẽ được sắp xếp từ truy cập ít nhất đến truy cập gần đây nhất.
Tạo Bản đồ liên kết từ Bản đồ khác
Đây là cách chúng ta có thể tạo một bản đồ băm được liên kết chứa tất cả các phần tử của các bản đồ khác.
import java.util.LinkedHashMap;
class Main {
public static void main(String[] args) {
// Creating a LinkedHashMap of even numbers
LinkedHashMap<String, Integer> evenNumbers = new LinkedHashMap<>();
evenNumbers.put("Two", 2);
evenNumbers.put("Four", 4);
System.out.println("LinkedHashMap1: " + evenNumbers);
// Creating a LinkedHashMap from other LinkedHashMap
LinkedHashMap<String, Integer> numbers = new LinkedHashMap<>(evenNumbers);
numbers.put("Three", 3);
System.out.println("LinkedHashMap2: " + numbers);
}
}
Đầu ra
LinkedHashMap1: {Two=2, Four=4} LinkedHashMap2: {Two=2, Four=4, Three=3}
Phương thức của LinkedHashMap
Các LinkedHashMap
lớp học cung cấp phương pháp đó cho phép chúng tôi thực hiện các hoạt động khác nhau trên bản đồ.
Chèn các phần tử vào LinkedHashMap
put()
– inserts the specified key/value mapping to the mapputAll()
– inserts all the entries from the 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.LinkedHashMap;
class Main {
public static void main(String[] args) {
// Creating LinkedHashMap of even numbers
LinkedHashMap<String, Integer> evenNumbers = new LinkedHashMap<>();
// Using put()
evenNumbers.put("Two", 2);
evenNumbers.put("Four", 4);
System.out.println("Original LinkedHashMap: " + evenNumbers);
// Using putIfAbsent()
evenNumbers.putIfAbsent("Six", 6);
System.out.println("Updated LinkedHashMap(): " + evenNumbers);
//Creating LinkedHashMap of numbers
LinkedHashMap<String, Integer> numbers = new LinkedHashMap<>();
numbers.put("One", 1);
// Using putAll()
numbers.putAll(evenNumbers);
System.out.println("New LinkedHashMap: " + numbers);
}
}
Đầu ra
Original LinkedHashMap: {Two=2, Four=4} Updated LinkedHashMap: {Two=2, Four=4, Six=6} New LinkedHashMap: {One=1, Two=2, Four=4, Six=6}
Truy cập các phần tử LinkedHashMap
1. Sử dụng entrySet (), keySet () và các giá trị ()
entrySet()
– returns a set of all the key/value mapping of the mapkeySet()
– returns a set of all the keys of the mapvalues()
– returns a set of all the values of the map
Ví dụ,
import java.util.LinkedHashMap;
class Main {
public static void main(String[] args) {
LinkedHashMap<String, Integer> numbers = new LinkedHashMap<>();
numbers.put("One", 1);
numbers.put("Two", 2);
numbers.put("Three", 3);
System.out.println("LinkedHashMap: " + 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
LinkedHashMap: {One=1, Two=2, Three=3} Key/Value mappings: [One=1, Two=2, Three=3] Keys: [One, Two, Three] Values: [1, 2, 3]
2. Sử dụng get () và getOrDefault ()
get()
– Returns the value associated with the specified key. If the key is not found, it returnsnull
.getOrDefault()
– Returns the value associated with the specified key. If the key is not found, it returns the specified default value.
Ví dụ,
import java.util.LinkedHashMap;
class Main {
public static void main(String[] args) {
LinkedHashMap<String, Integer> numbers = new LinkedHashMap<>();
numbers.put("One", 1);
numbers.put("Two", 2);
numbers.put("Three", 3);
System.out.println("LinkedHashMap: " + numbers);
// Using get()
int value1 = numbers.get("Three");
System.out.println("Returned Number: " + value1);
// Using getOrDefault()
int value2 = numbers.getOrDefault("Five", 5);
System.out.println("Returned Number: " + value2);
}
}
Đầu ra
LinkedHashMap: {One=1, Two=2, Three=3} Returned Number: 3 Returned Number: 5
Đã xóa phần tử bản đồ liên kết
remove(key)
– returns and removes the entry associated with the specified key from the mapremove(key, value)
– removes the entry from the map only if the specified key mapped to be the specified value and return a boolean value
Ví dụ,
import java.util.LinkedHashMap;
class Main {
public static void main(String[] args) {
LinkedHashMap<String, Integer> numbers = new LinkedHashMap<>();
numbers.put("One", 1);
numbers.put("Two", 2);
numbers.put("Three", 3);
System.out.println("LinkedHashMap: " + 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 removed? " + result);
System.out.println("Updated LinkedHashMap: " + numbers);
}
}
Đầu ra
LinkedHashMap: {One=1, Two=2, Three=3} Removed value: 2 Is the entry {Three=3} removed? True Updated LinkedHashMap: {One=1}
Các phương pháp khác của LinkedHashMap
Method | Decfscription |
---|---|
clear() | removes all the entries from the map |
containsKey() | checks if the map contains the specified key and returns a boolean value |
containsValue() | checks if the map contains the specified value and returns a boolean value |
size() | returns the size of the map |
isEmpty() | checks if the map is empty and returns a boolean value |
LinkedHashMap Vs. Bản đồ băm
Cả cái LinkedHashMap
và cái đều HashMap
triển khai Map
giao diện. Tuy nhiên, tồn tại một số khác biệt giữa chúng.
LinkedHashMap
maintains a doubly-linked list internally. Due to this, it maintains the insertion order of its elements.- The
LinkedHashMap
class requires more storage thanHashMap
. This is becauseLinkedHashMap
maintains linked lists internally. - The performance of
LinkedHashMap
is slower thanHashMap
.