Computer >> Hướng Dẫn Máy Tính >  >> Lập Trình >> Java

Các factory methods thêm cho Collections trong Java 9

Factory methods là loại phương thức tĩnh đặc biệt dùng để tạo instance unmodifiable (không thể sửa đổi) của collections. Nghĩa là dùng các phương thức này tạo list, set và map với số lượng phần tử nhỏ.

List.of()

List.of() là factory method tĩnh tạo immutable lists thuận tiện.

Cú pháp

List.of(elements...)

Ví dụ

import java.util.List;

public class ListTest {
    public static void main(String[] args) {
        List<String> list = List.of("item 1", "item 2", "item 3", "item 4", "item 5");
        for(String l : list) {
            System.out.println(l);
        }
    }
}

Kết quả

item 1
item 2
item 3
item 4
item 5

Set.of()

Set.of() là factory method tĩnh tạo immutable sets thuận tiện.

Cú pháp

Set.of(elements...)

Ví dụ

import java.util.Set;

public class SetTest {
    public static void main(String[] args) {
        Set<String> set = Set.of("Item 1", "Item 2", "Item 3", "Item 4", "Item 5");
        for(String s : set) {
            System.out.println(s);
        }
    }
}

Kết quả

Item 5
Item 1
Item 2
Item 3
Item 4

Map.of() và Map.ofEntries()

Map.of() và Map.ofEntries() là factory methods tĩnh tạo immutable maps thuận tiện.

Cú pháp

Map.of(k1, v1, k2, v2)
Map.ofEntries(entry(k1, v1), entry(k2, v2),...)

Ví dụ

import java.util.Map;

public class MapTest {
    public static void main(String[] args) {
        Map<Integer, String> map = Map.of(101, "Raja", 102, "Adithya", 103, "Jai");
        for(Map.Entry<Integer, String> m : map.entrySet()) {
            System.out.println(m.getKey() + " " + m.getValue());
        }
    }
}

Kết quả

103 Jai
102 Adithya
101 Raja