我想打印一些我从文本文件传递给 map 的数据。但是,当我打印数据时,程序会打印两次行。有什么办法可以解决吗?我只想以准确的方式打印数据,不要重复。
import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.*;
public class ReadToHashmap {
public static void main(String[] args) throws Exception
{
Map<String, String> map = new HashMap<>();
final BufferedReader bufferedReader = new BufferedReader(new FileReader("C:\\Documents and Settings\\stajn\\Desktop\\Cache_Son\\Cache\\Testing.txt"));
if (bufferedReader != null) {
String line;
while ((line = bufferedReader.readLine()) != null) {
String parts[] = line.split("\n");
map.put(parts[0],parts[0]);
}
bufferedReader.close();
Iterator iterator = map.keySet().iterator();
while (iterator.hasNext())
{
String key = iterator.next().toString();
String value = map.get(key).toString();
System.out.println(key + " " + value);
}
}
}
}
最佳答案
你正在像这样放置 map
map.put(parts[0],parts[0]);
所以这里 Key 和 value 是一样的。当你打印的时候
System.out.println(key + " " + value);
两者将打印相同的内容。
你需要吗?
System.out.println("value=" + value);
关于java - 从 JAVA 中的 MAP 打印,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18608989/