java一對(duì)多映射怎么實(shí)現(xiàn)

小億
86
2023-12-05 11:54:00

在Java中實(shí)現(xiàn)一對(duì)多映射可以使用Map接口的實(shí)現(xiàn)類HashMap或者LinkedHashMap。

  1. 使用HashMap實(shí)現(xiàn)一對(duì)多映射:
import java.util.*;

public class OneToManyMapping {
    public static void main(String[] args) {
        Map<String, List<String>> map = new HashMap<>();

        // 添加一對(duì)多映射關(guān)系
        map.put("key1", new ArrayList<>(Arrays.asList("value1", "value2")));
        map.put("key2", new ArrayList<>(Arrays.asList("value3")));
        map.put("key3", new ArrayList<>(Arrays.asList("value4", "value5", "value6")));

        // 獲取key對(duì)應(yīng)的多個(gè)value
        List<String> values = map.get("key1");
        System.out.println(values); // [value1, value2]

        // 添加新的value到key對(duì)應(yīng)的多個(gè)value中
        map.get("key1").add("value3");
        System.out.println(map.get("key1")); // [value1, value2, value3]

        // 遍歷一對(duì)多映射
        for (Map.Entry<String, List<String>> entry : map.entrySet()) {
            String key = entry.getKey();
            List<String> valueList = entry.getValue();
            System.out.println(key + ": " + valueList);
        }
    }
}
  1. 使用LinkedHashMap實(shí)現(xiàn)一對(duì)多映射:
import java.util.*;

public class OneToManyMapping {
    public static void main(String[] args) {
        Map<String, List<String>> map = new LinkedHashMap<>();

        // 添加一對(duì)多映射關(guān)系
        map.put("key1", new ArrayList<>(Arrays.asList("value1", "value2")));
        map.put("key2", new ArrayList<>(Arrays.asList("value3")));
        map.put("key3", new ArrayList<>(Arrays.asList("value4", "value5", "value6")));

        // 獲取key對(duì)應(yīng)的多個(gè)value
        List<String> values = map.get("key1");
        System.out.println(values); // [value1, value2]

        // 添加新的value到key對(duì)應(yīng)的多個(gè)value中
        map.get("key1").add("value3");
        System.out.println(map.get("key1")); // [value1, value2, value3]

        // 遍歷一對(duì)多映射
        for (Map.Entry<String, List<String>> entry : map.entrySet()) {
            String key = entry.getKey();
            List<String> valueList = entry.getValue();
            System.out.println(key + ": " + valueList);
        }
    }
}

以上兩種實(shí)現(xiàn)方式都可以實(shí)現(xiàn)一對(duì)多映射,其中HashMap是無(wú)序的,而LinkedHashMap是有序的,根據(jù)插入順序排序。根據(jù)需求選擇合適的實(shí)現(xiàn)類。

0