当我使用下面的代码遍历我的hashmap列表时,我得到了键和值
System.out.println( " (" + key + "," + value + ")" )
但我希望我的值以
的形式返回关键1:价值1
关键1:价值2
关键2:价值1
关键2:价值2 ......等等。有人可以帮助我。
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();
}
答案 0 :(得分:2)
替换它:
System.out.println( " (" + key + "," + value + ")" );
与
for (Object listItem : (List)value) {
System.out.println(key + ":" + listItem);
}
答案 1 :(得分:0)
使用LinkedHashMap
,地图中put
个条目的顺序与迭代它们的顺序相同。
答案 2 :(得分:0)
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) + ")" );
}
}
答案 3 :(得分:0)
所以你想打印列表中的值?替换:
Object value = entry.getValue(); // Get the value.
System.out.println( " (" + key + "," + value + ")" );
有了这个:
List<String> value = entry.getValue();
for(String s : value) {
System.out.println(key + ": " + s);
}