首页 > 解决方案 > 将 Hashmap 上的列表添加到另一个列表时出现问题

问题描述

将列表从一个哈希映射的值添加到另一个哈希映射的问题

基本上,我有 2 个哈希图(map1 和 map2),它们都有相同的键(0-500 的整数),但值不同。我想要做的是使用 map1 的值,它是一个字符串,作为键和 map2 的值,它是一个列表,作为值。添加 map1 作为键是有效的,没问题,但是当我尝试将 map2 的值添加为 map 的值时,它只是返回为 null。

这是一个家庭作业项目,我们有 2 个 .csv 文件,一个带有标签,另一个带有假图像文件名,并且必须能够通过图像标签或图像文件名进行搜索。

Map<String, List<String>> map = new HashMap<String, List<String>>();

    @SuppressWarnings({ "resource", "null", "unlikely-arg-type" })
    public ImageLabelReader(String labelMappingFile, String imageMappingFile) throws IOException {
        Map<Integer, String> map1 = new HashMap<Integer, String>();
        Map<Integer, List<String>> map2 = new HashMap<Integer, List<String>>();
        BufferedReader labelIn = new BufferedReader(new FileReader(labelMappingFile));
        BufferedReader imageIn = new BufferedReader(new FileReader(imageMappingFile));
        String row;
        String[] rowArray;
        while ((row = labelIn.readLine()) != null) {
            rowArray = row.split(" ", 2);
            map1.put(Integer.parseInt(rowArray[0]), rowArray[1]);
            }
        labelIn.close();
        while ((row = imageIn.readLine()) != null) {
            rowArray = row.split(" ", 2);
            if(map2.containsKey(Integer.parseInt(rowArray[1]))) {
                List<String> tempList = map2.get(Integer.parseInt(rowArray[1]));
                tempList.add(rowArray[0]);
            } else {
                List<String> l = new ArrayList<String>();
                l.add(rowArray[0]);
                map2.put(Integer.parseInt(rowArray[1]), l);
            }
        }
        imageIn.close();
        List<String> t = new ArrayList<String>();
        for(int i = 0; i < map1.size(); i++) {
            t.clear();
            for(String s : map2.get(i)) {
                t.add(s);
                System.out.println(t);
            }

            map.put(map1.get(i), map2.get(i));

        }

        System.out.println(map.containsKey("burrito"));
        System.out.print(map2.get("burrito"));
    }

当输出应为“True [包含字符串的列表]”时,输出为“True null”

标签: javalistarraylisthashmap

解决方案


尝试更换 -

map.put(map1.get(i), map2.get(i));

map.put(map1.get(i), t);

并且 -

System.out.print(map2.get("burrito"));

System.out.print(map.get("burrito"));

此外,您正在尝试使用String您所说的密钥int类型来获取地图的值,请检查。


推荐阅读