目前我有这个:
try{
// Create file
FileWriter fstream = new FileWriter("output");
BufferedWriter out = new BufferedWriter(fstream);
Iterator mapIt = assignments.entrySet().iterator();
while (mapIt.hasNext()){
out.write(mapIt.next().toString()+";\n");
}
//Close the output stream
out.close();
}
问题是,我不能只使用迭代器的 toString(),我需要分别取出键和值,这样我就可以在输出文件中将它们之间放一些东西。有谁知道我该怎么做?
最佳答案
您会注意到迭代器返回一个 Map.Entry它有 getKey
和 getValue
方法。
使用它们来获取相应的项目....类似
while (mapIt.hasNext()){
Map.Entry entry = mapIt.next();
Object key = entry.getKey();
Object value = entry.getValue();
// format away..
}
请注意,我将 Object
作为键和值的类型,但您应该根据您定义 Map 的方式指定类型。
关于java - 如何遍历 LinkedHashMap 并分别在键和值之间进行选择?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9332206/