API Collections trong Java
Collections Framework trong Java là một tập hợp các interface và class được thiết kế để lưu trữ và xử lý nhóm các đối tượng. Nó cung cấp các cấu trúc dữ liệu phổ biến như List, Set, Map và các thuật toán để thao tác với chúng.
1. Interface Cơ Bản
Collection Interface
Collection<String> collection = new ArrayList<>();
collection.add("Java");
collection.add("Python");
collection.add("JavaScript");
// Kiểm tra phần tử
boolean contains = collection.contains("Java"); // true
boolean isEmpty = collection.isEmpty(); // false
int size = collection.size(); // 3
// Xóa phần tử
collection.remove("Python");
collection.clear(); // Xóa tất cả
List Interface
List<String> list = new ArrayList<>();
list.add("Java");
list.add(0, "Python"); // Thêm vào vị trí cụ thể
list.set(1, "JavaScript"); // Cập nhật phần tử
// Truy cập phần tử
String first = list.get(0); // "Python"
int index = list.indexOf("JavaScript"); // 1
Set Interface
Set<String> set = new HashSet<>();
set.add("Java");
set.add("Python");
set.add("Java"); // Không thêm vào vì đã tồn tại
// Kiểm tra phần tử
boolean exists = set.contains("Python"); // true
Map Interface
Map<String, Integer> map = new HashMap<>();
map.put("Java", 1);
map.put("Python", 2);
// Truy cập giá trị
Integer value = map.get("Java"); // 1
boolean containsKey = map.containsKey("Python"); // true
2. Collection Classes
ArrayList
ArrayList<String> list = new ArrayList<>();
list.add("Java");
list.add("Python");
list.add("JavaScript");
// Duyệt qua ArrayList
for (String item : list) {
System.out.println(item);
}
// Sử dụng Iterator
Iterator<String> iterator = list.iterator();
while (iterator.hasNext()) {
System.out.println(iterator.next());
}
LinkedList
LinkedList<String> list = new LinkedList<>();
list.addFirst("Java");
list.addLast("Python");
list.add("JavaScript");
// Thao tác với đầu và cuối
String first = list.getFirst();
String last = list.getLast();
list.removeFirst();
list.removeLast();
HashSet
HashSet<String> set = new HashSet<>();
set.add("Java");
set.add("Python");
set.add("JavaScript");
// Kiểm tra phần tử
boolean exists = set.contains("Python");
// Duyệt qua HashSet
for (String item : set) {
System.out.println(item);
}
HashMap
HashMap<String, Integer> map = new HashMap<>();
map.put("Java", 1);
map.put("Python", 2);
map.put("JavaScript", 3);
// Duyệt qua key
for (String key : map.keySet()) {
System.out.println(key + ": " + map.get(key));
}
// Duyệt qua entry
for (Map.Entry<String, Integer> entry : map.entrySet()) {
System.out.println(entry.getKey() + ": " + entry.getValue());
}
3. Collection Classes Đặc Biệt
TreeSet
TreeSet<String> set = new TreeSet<>();
set.add("Java");
set.add("Python");
set.add("JavaScript");
// Lấy phần tử đầu và cuối
String first = set.first(); // "Java"
String last = set.last(); // "Python"
// Lấy subset
SortedSet<String> subset = set.subSet("Java", "Python");
TreeMap
TreeMap<String, Integer> map = new TreeMap<>();
map.put("Java", 1);
map.put("Python", 2);
map.put("JavaScript", 3);
// Lấy key đầu và cuối
String firstKey = map.firstKey(); // "Java"
String lastKey = map.lastKey(); // "Python"
// Lấy submap
SortedMap<String, Integer> submap = map.subMap("Java", "Python");
PriorityQueue
PriorityQueue<Integer> queue = new PriorityQueue<>();
queue.offer(5);
queue.offer(2);
queue.offer(8);
// Lấy và xóa phần tử nhỏ nhất
while (!queue.isEmpty()) {
System.out.println(queue.poll()); // In: 2, 5, 8
}
4. Utility Classes
Collections
List<String> list = new ArrayList<>();
list.add("Java");
list.add("Python");
list.add("JavaScript");
// Sắp xếp
Collections.sort(list);
// Đảo ngược
Collections.reverse(list);
// Tìm kiếm nhị phân
int index = Collections.binarySearch(list, "Python");
// Tạo collection không thể sửa đổi
List<String> immutableList = Collections.unmodifiableList(list);
Arrays
String[] array = {"Java", "Python", "JavaScript"};
// Chuyển đổi mảng thành List
List<String> list = Arrays.asList(array);
// Sắp xếp mảng
Arrays.sort(array);
// Tìm kiếm nhị phân
int index = Arrays.binarySearch(array, "Python");
5. Ví Dụ Thực Tế
Quản Lý Danh Sách Sản Phẩm
public class Product {
private String id;
private String name;
private double price;
// Constructor và getter/setter
}
public class ProductManager {
private List<Product> products = new ArrayList<>();
public void addProduct(Product product) {
products.add(product);
}
public Product findProduct(String id) {
return products.stream()
.filter(p -> p.getId().equals(id))
.findFirst()
.orElse(null);
}
public List<Product> getProductsByPriceRange(double min, double max) {
return products.stream()
.filter(p -> p.getPrice() >= min && p.getPrice() <= max)
.collect(Collectors.toList());
}
}
Quản Lý Đơn Hàng
public class Order {
private String orderId;
private Map<String, Integer> items = new HashMap<>();
public void addItem(String productId, int quantity) {
items.merge(productId, quantity, Integer::sum);
}
public void removeItem(String productId) {
items.remove(productId);
}
public int getTotalItems() {
return items.values().stream()
.mapToInt(Integer::intValue)
.sum();
}
}
6. Best Practices
-
Chọn Collection Phù Hợp
// Không nên
List<String> list = new ArrayList<>(); // Khi cần Set
// Nên
Set<String> set = new HashSet<>(); // Khi cần Set -
Sử Dụng Generic Types
// Không nên
List list = new ArrayList();
// Nên
List<String> list = new ArrayList<>(); -
Xử Lý Null Safety
// Không nên
if (list.contains(null)) { }
// Nên
if (list != null && !list.isEmpty()) { }
7. Lỗi Thường Gặp
-
ConcurrentModificationException
// Lỗi
for (String item : list) {
list.remove(item); // ConcurrentModificationException
}
// Đúng
Iterator<String> iterator = list.iterator();
while (iterator.hasNext()) {
iterator.next();
iterator.remove();
} -
NullPointerException
// Lỗi
List<String> list = null;
list.add("Java"); // NullPointerException
// Đúng
List<String> list = new ArrayList<>();
list.add("Java"); -
ClassCastException
// Lỗi
List list = new ArrayList();
list.add("Java");
Integer number = (Integer) list.get(0); // ClassCastException
// Đúng
List<String> list = new ArrayList<>();
list.add("Java");
String str = list.get(0);