Reputation: 11
When I iterate over my hashmap list with the below code, I get the key and values as
System.out.println( " (" + key + "," + value + ")" )
But I want my values to be returned as
Key 1:value 1
Key 1:value 2
Key 2:value 1
Key 2:value 2... so on. Can some one help me out.
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]));
}
}
}
Set<Entry<String, List<String>>> entries =PropertyMap.entrySet();
Iterator<Entry<String, List<String>>> entryIter = entries.iterator();
System.out.println("The map contains the following associations:");
while (entryIter.hasNext()) {
Map.Entry entry = (Map.Entry)entryIter.next();
Object key = entry.getKey(); // Get the key from the entry.
Object value = entry.getValue(); // Get the value.
System.out.println( " (" + key + "," + value + ")" );
}
scanner.close();
}
catch (Exception e) {
e.printStackTrace();
}
Upvotes: 0
Views: 147
Reputation: 3880
So you want to print out the values in your Lists? Replace:
Object value = entry.getValue(); // Get the value.
System.out.println( " (" + key + "," + value + ")" );
With this:
List<String> value = entry.getValue();
for(String s : value) {
System.out.println(key + ": " + s);
}
Upvotes: 0
Reputation: 6053
while (entryIter.hasNext()) {
//...
String key = entry.getKey(); // Get the key from the entry.
List<String> value = entry.getValue(); // Get the value.
for(int i = 0; i < value.size(); i++) {
System.out.println( " (" + key + "," + value.get(i) + ")" );
}
}
Upvotes: 0
Reputation: 23265
Replace this:
System.out.println( " (" + key + "," + value + ")" );
with
for (Object listItem : (List)value) {
System.out.println(key + ":" + listItem);
}
Upvotes: 2
Reputation: 30042
Use a LinkedHashMap
and the order you put
entries in the map will be the same order you iterate over them.
Upvotes: 0