2012-08-23 53 views
0

我想知道如果我可以访问下面的代码(我知道它们存储在地图中,但想要在循环外使用它们)迭代哈希映射后得到的值。键和相应的值在循环内迭代。并发散列表可以帮助我获取值并在循环外部使用它们。使用并发散列表

谢谢。

 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(); 
      } 

     } 
+1

你实际上使用多个线程吗? – SLaks

+1

a)ConcurrentHashMap是一个线程安全的映射,这看起来并不多线程化,并且b)两个循环中的哪一个?和c)什么变量? – Dan

回答

2

ConcurrentHashMap被设计成线程安全的。
如果你不使用多线程,它比无用的更糟糕。您可以使用MultiMap

您可以总是循环外的访问值。