So sánh hashmap và treemap trong java

Các entry trong HashMap không được sắp xếp theo thứ tự. Nhưng nếu bạn bị yêu cầu phải sắp xếp thì bạn hoàn toàn có thể làm được.

Sắp xếp HashMap dựa trên các Keys khá là dễ. Chúng ta có 2 cách làm.

Cách 1: Dùng TreeMap (ưu tiên dùng cách này)

Việc bạn cần làm là tạo ra một TreeMap bằng cách sao chép các entries từ HashMap.

TreeMap là một implementation của SortedMap. Vì vậy nó sẽ sắp xếp theo natural ordering hoặc bạn hoàn toàn có thể custom việc sắp xếp theo ý bạn bằng cách dùng Comparator.

Cách 2: Dùng LinkedHashMap

Cách này hơi dài dòng chút. Đầu tiên bạn cần lấy ra một Set các keys. Convert Set đó thành List. Sắp xếp List đó, và rồi add chúng lại LinkedHashMap theo đúng thứ tự đã sắp xếp.

2. Sắp xếp HashMap dựa trên Value

Sắp xếp dựa trên Value khá phức tạp vì không có phương pháp trực tiếp hỗ trợ việc này. Bạn buộc phải viết code cho nó. Đầu tiên bạn phải tạo ra một Comparator để so sánh hai entries dựa trên value. Sau đó lấy Set of entries từ Map, convert Set thành List và dùng phương thức Collections.sort(List) để sắp xếp List các entries bằng value bằng cách truyền vào customized value comparator. Việc này tương tự như Làm thế nào để sắp xếp một ArrayList trong Java?

Cuối cùng, chúng ta tạo ra một LinkedHashMap, đây là một lớp extend từ HashMap và add các entries đã được sắp xếp vào đó. LinkedHashMap sẽ đảm bảo các phần tử được chèn vào theo một thứ tự 😉

Nội dung

Đặc điểm

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

  • TreeMap lưu trữ dữ liệu dưới dạng cặp key và value.
  • TreeMap chỉ chứa các key duy nhất.
  • TreeMap KHÔNG cho phép bất kỳ key nào là null và nhưng có thể có nhiều giá trị null.
  • TreeMap duy trì các phần tử được thêm vào theo thứ tự key tăng dần.

Hierarchy của lớp TreeMap

So sánh hashmap và treemap trong java

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

public class TreeMap

extends AbstractMap
implements NavigableMap, Cloneable, java.io.Serializable {
}

Trong đó:

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

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

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

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

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

Ví dụ minh họa

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

package com.gpcoder.collection.treemap; import java.util.Map; import java.util.Map.Entry; import java.util.TreeMap; public class LinkedHashMapExample { public static void main(String args[]) {

// init map
Map map = new TreeMap();
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 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 3 = Collection 4 = Multi-Thread


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

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

package com.gpcoder.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.gpcoder.collection.treemap; import java.util.Map; import java.util.Map.Entry; import java.util.TreeMap; 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 map = new TreeMap();
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 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] 3 = Student [id=3, name=Student 3] 4 = Student [id=4, name=Student 4]


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

Chuyên mục: Collection Được gắn thẻ: Collection

Bình luận

bình luận