Reputation: 11
I want to iterate over the HashMap list and retrieve the key and the values (value 1 and value2). There is a error at this line that says "Type mismatch: cannot convert from element type Object to Map.Entry>"
for (Map.Entry<String, List<String>> entry : Map.entrySet())
Am I doing anything wrong. Please help me out. Here is the entire code.
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();
}
Upvotes: 0
Views: 828
Reputation: 1
Map.entrySet() returns a collection view of the map.change it in to conceptMap.entrySet() or propertyMap.entrySet
Upvotes: 0
Reputation: 53
Change Map.entrySet()
to PropertyMap.entrySet()
or conceptMap.entrySet()
Upvotes: 2
Reputation: 6053
The Map.entrySet()
method declared by the Map interface returns a collection-view of the map (returns a Set
). Each of these set elements is a Map.Entry
object. The only way to obtain a reference to a map entry is from the iterator of this collection-view.
If you want to return a Set
you inserted into the map, you have to call it on the Collection you placed it in:
PropertyMap.entrySet()
and conceptMap.entrySet()
will return Sets.
Map.entrySet()
is not calling the method on either of your instantiated Maps
.
Upvotes: 1