我想知道是否可以访问在以下代码中迭代 hashmap 后获得的值(我知道它们存储在 map 中但想在循环外使用它们)。键和对应的值在循环内迭代。并发哈希图可以帮助我获取值并在循环外使用它们。
谢谢你。
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();
}
}