Lớp LinkedHashMap trong Java

1. Đặc điểm

Những điểm quan trọng về lớp LinkedHashMap trong java cần nhớ là:

  • LinkedHashMap lưu trữ dữ liệu dưới dạng cặp key và value.
  • LinkedHashMap chỉ chứa các key duy nhất.
  • LinkedHashMap có thể có 1 key là null và nhiều giá trị null.
  • LinkedHashMap duy trì các phần tử theo thứ tự chèn.

2. Hierarchy của lớp LinkedHashMap

linkedhashmap

Lớp java.util.LinkedHashMap được định nghĩa như sau:

public class LinkedHashMap<K,V> 
    extends HashMap<K,V> implements Map<K,V> {
     
}

Trong đó:

  • K: đây là kiểu key để lưu trữ.
  • V: đây là kiểu giá trị được ánh xạ.

3. Các phương thức khởi tạo (constructor) của lớp LinkedHashMap

  • LinkedHashMap(): khởi tạo một map trống.
  • LinkedHashMap(Map<? extends K, ? extends V> m): khởi tạo một map với các phần tử của map m.

4. Các phương thức (method) của lớp LinkedHashMap

Xem thêm các phương thức của Map ở bài viết Map Interface trong java.

5. Ví dụ minh họa

5.1. Ví dụ sử dụng LinkedHashMap với kiểu dữ liệu cơ bản (Wrapper)

package com.maixuanviet.collection.linkedhashmap;
 
import java.util.LinkedHashMap;
import java.util.Map;
import java.util.Map.Entry;
 
public class LinkedHashMapExample {
    public static void main(String args[]) {
        // init map
        Map<Integer, String> map = new LinkedHashMap<Integer, String>();
        map.put(1, "Basic java");
        map.put(2, "OOP");
        map.put(4, "Multi-Thread");
        map.put(3, "Collection");
 
        // show map using method keySet()
        for (Integer key : map.keySet()) {
            String value = map.get(key);
            System.out.println(key + " = " + value);
        }
 
        System.out.println("---");
 
        // show map using method keySet()
        for (Entry<Integer, String> entry : map.entrySet()) {
            Integer key = entry.getKey();
            String value = entry.getValue();
            System.out.println(key + " = " + value);
        }
    }
}

Kết quả thực thi chương trình trên:

1 = Basic java
2 = OOP
4 = Multi-Thread
3 = Collection
---
1 = Basic java
2 = OOP
4 = Multi-Thread
3 = Collection

5.2. Ví dụ sử dụng LinkedHashMap với key có kiểu String, value có kiểu Student

package com.maixuanviet.collection.map;
 
public class Student {
    private int id;
    private String name;
 
    public Student(int id, String name) {
        this.id = id;
        this.name = name;
    }
 
    @Override
    public String toString() {
        return "Student [id=" + id + ", name=" + name + "]";
    }
 
    public int getId() {
        return id;
    }
 
    public String getName() {
        return name;
    }
 
}
package com.maixuanviet.collection.linkedhashmap;
 
import java.util.LinkedHashMap;
import java.util.Map;
import java.util.Map.Entry;
 
public class LinkedHashMapExample2 {
    public static void main(String args[]) {
        // Student's data
        Student student1 = new Student(1, "Student 1");
        Student student2 = new Student(2, "Student 2");
        Student student3 = new Student(3, "Student 3");
        Student student4 = new Student(4, "Student 4");
 
        // init map
        Map<Integer, Student> map = new LinkedHashMap<Integer, Student>();
        map.put(student1.getId(), student1);
        map.put(student2.getId(), student2);
        map.put(student4.getId(), student4);
        map.put(student3.getId(), student3);
 
        // show map using method keySet()
        for (Integer key : map.keySet()) {
            Student value = map.get(key);
            System.out.println(key + " = " + value);
        }
 
        System.out.println("---");
 
        // show map using method keySet()
        for (Entry<Integer, Student> entry : map.entrySet()) {
            Integer key = entry.getKey();
            Student value = entry.getValue();
            System.out.println(key + " = " + value);
        }
    }
 
}

Kết quả thực thi chương trình trên:

1 = Student [id=1, name=Student 1]
2 = Student [id=2, name=Student 2]
4 = Student [id=4, name=Student 4]
3 = Student [id=3, name=Student 3]
---
1 = Student [id=1, name=Student 1]
2 = Student [id=2, name=Student 2]
4 = Student [id=4, name=Student 4]
3 = Student [id=3, name=Student 3]

Related posts:

Spring Boot - Enabling HTTPS
Java Program to Check if a Directed Graph is a Tree or Not Using DFS
Java Program to Implement LinkedTransferQueue API
Extract links from an HTML page
Spring Security OAuth2 – Simple Token Revocation
Reversing a Linked List in Java
Java Program to Implement Radix Sort
Java Program to Compute the Volume of a Tetrahedron Using Determinants
Sao chép các phần tử của một mảng sang mảng khác như thế nào?
A Guide to the ViewResolver in Spring MVC
Java Program to Search Number Using Divide and Conquer with the Aid of Fibonacci Numbers
Anonymous Classes in Java
Jackson JSON Views
Java Program to Find Basis and Dimension of a Matrix
The Spring @Controller and @RestController Annotations
Spring Data JPA Delete and Relationships
Custom Thread Pools In Java 8 Parallel Streams
Tạo ứng dụng Java RESTful Client với thư viện Retrofit
Sorting Query Results with Spring Data
Spring RestTemplate Request/Response Logging
Lập trình đa luồng với CompletableFuture trong Java 8
Java Program to Perform Polygon Containment Test
REST Web service: Upload và Download file với Jersey 2.x
Split a String in Java
Java 8 Collectors toMap
Java Program to Solve any Linear Equation in One Variable
Java Program to Implement Bresenham Line Algorithm
Guide to the Java Clock Class
Deploy a Spring Boot App to Azure
Java Program to Implement the linear congruential generator for Pseudo Random Number Generation
Java Program to Implement vector
Java Program to Represent Graph Using Incidence List