我想知道在以下代码中迭代hashmap之后是否可以访问我得到的值(我知道它们存储在map中但是想在循环外使用它们)。密钥和相应的值在循环内迭代。并发hashmap可以帮助我获取值并在循环外使用它们。
谢谢。
public static void main(String[] args) {
Map<String, List<String>> maleMap = new LinkedHashMap<String, List<String>>();
Map<String, List<String>> femaleMap = new LinkedHashMap<String, List<String>>();
try {
Scanner scanner = new Scanner(new FileReader(.txt));
while (scanner.hasNextLine()) {
String nextLine = scanner.nextLine();
String[] column = nextLine.split(":");
if (column[0].equals("male") && (column.length == 4)) {
maleMap.put(column[1],
Arrays.asList(column[2], column[3]));
} else if (column[0].equals("female") && (column.length == 4)) {
femaleMap.put(column[1],
Arrays.asList(column[2], column[3]));
}
}
Set<Entry<String, List<String>>> entries = maleMap.entrySet();
Iterator<Entry<String, List<String>>> entryIter = entries
.iterator();
while (entryIter.hasNext()) {
Map.Entry entry = (Map.Entry) entryIter.next();
Object key = entry.getKey(); // Get the key from the entry.
List<String> value = (List<String>) entry.getValue();
Object value1 = " ";
Object value2 = " ";
int counter = 0;
for (Object listItem : (List) value) {
Writer writer = null;
Object Name = key;
Object Age = null;
Object ID = null;
if (counter == 0) {// first pass assign value to value1
value1 = listItem;
counter++;// increment for next pass
} else if (counter == 1) {// second pass assign value to
// value2
value2 = listItem;
counter++;// so we dont keep re-assigning listItem for
// further iterations
}
}
System.out.println(key + ":" + value1 + "," + value2);
scanner.close();
Writer writer = null;
Object Name = key;
Object Age = value1;
Object ID = value2;
try {
String filename = ".txt";
FileWriter fw = new FileWriter(filename, true);
fw.write("# Table" + Name + "\n" + "map:"+ Name + " a d2rq:ClassMap;" + "\n"
+ " dataStorage map:database;" + "\n"+ "Pattern " +"\""+ Name + "/@@"+ Age +
"." + ID + "@@\";" + "\n"+ " class :" + Name +";"+"\n"+ " ."+"\n");//
fw.close();
} catch (Exception e) {
e.printStackTrace();
}
}
答案 0 :(得分:2)
ConcurrentHashMap
旨在确保线程安全
如果你没有使用多个线程,那就更糟糕了。
您应该使用MultiMap
。
您可以始终访问循环外的值。
答案 1 :(得分:0)
ConcorrentHashMap是故障安全的。它不会给出任何并发的修改异常。它适用于多线程操作。 ConcurrentHashMap的整个实现与HashMap相同,但是在检索元素的同时,HashMap锁定整个映射,限制了进行进一步的修改,从而导致并发修改异常。但是在ConcurrentHashMap中,锁定发生在存储桶级别,因此不存在提供并发修改异常的机会。