在hashmap列表上进行迭代



我想迭代HashMap列表并检索键和值(值1和值2)。这一行有一个错误,上面写着"类型不匹配:无法从元素类型Object转换为Map。Entry>"

for (Map.Entry<String, List<String>> entry : Map.entrySet()) 

我做错什么了吗。请帮帮我。这是整个代码。

public static void main(String[] args)  {
    Map<String, List<String>> conceptMap = new HashMap<String, List<String>>();
    Map<String, List<String>> PropertyMap = new HashMap<String, List<String>>();
    try{
        Scanner scanner = new Scanner(new FileReader("C:/"));
        while (scanner.hasNextLine()){
            String nextLine = scanner.nextLine();
            String [] column = nextLine.split(":");
            if (column[0].equals ("Property")){
                if (column.length == 4) {
                    PropertyMap.put(column [1], Arrays.asList(column[2], column[3]));    
                }
                else {
                    conceptMap.put (column [1], Arrays.asList (column[2], column[3]));
                }
            }
            for (Map.Entry<String, List<String>> entry : Map.entrySet()) {
                String key = entry.getKey();
                List<String> valueList = entry.getValue();
                System.out.println("Key: " + key);
                System.out.print("Values: ");
                for (String s : valueList) {
                    System.out.print(s + " ");
                }
            }
        }
        scanner.close();
    }    
    catch (Exception e) {
        e.printStackTrace();
    }

Map.entrySet()更改为PropertyMap.entrySet()conceptMap.entrySet()

Map接口声明的Map.entrySet()方法返回映射的集合视图(返回Set)。这些集合元素中的每一个都是一个Map.Entry对象。获取映射条目引用的唯一方法是从此集合视图的迭代器。

如果你想返回你插入地图的Set,你必须在你放置它的集合上调用它:

PropertyMap.entrySet()conceptMap.entrySet()将返回Sets。

Map.entrySet()没有在任何一个实例化的Maps上调用该方法。

Map.entrySet()返回映射的集合视图。将其更改为conceptMap.entrtSet()或propertyMap.entrySet

最新更新