2016-08-18 33 views
-1

我有一張地圖(instaWords),它充滿了成千上萬的單詞。我需要一次循環它N項。這是我的代碼。在這段代碼中,我需要讀取例如500個字的塊中的instaWords,並用這些單詞執行「updateInstaPhrases」。任何幫助?閱讀地圖一次N鍵

private static Map<InstaWord, List<Integer>> instaWords = new HashMap<InstaWord, List<Integer>>(); 

// here a couple of words are added to instaWords 

updateInstaPhrases(instaWords);  

private static void updateInstaPhrases(Map<InstaWord, List<Integer>> wordMap)        
throws SQLException, UnsupportedEncodingException {          
    for (Map.Entry<InstaWord, List<Integer>> entry : wordMap.entrySet()) {    
     InstaWord instaWord = entry.getKey();          
     List<Integer> profiles = entry.getValue();          
     pst.setBytes(1, instaWord.word.getBytes("UTF-8"));       
     pst.setBytes(2, instaWord.word.getBytes("UTF-8"));       
     pst.setBytes(3, (instaWord.lang == null) ?·         
     "".getBytes("UTF-8") :·              
     instaWord.lang.getBytes("UTF-8"));           
     String profilesList = "";              
     boolean first = true;               
     for (Integer p : profiles) {             
      profilesList += (first ? "" : ", ") + p;           
      first = false;                 
     }                    
     pst.setString(4, profilesList);            
     pst.addBatch();                
    }                     
System.out.println("Words batch executed");           
pst.executeBatch();            
con.commit();                  
} 

我需要的是通過「以塊的形式」一個HashMap迭代(例如500每次項目)

+1

你應該修正你的縮進,這樣纔有意義。 – khelwood

+1

以防萬一你不知道...... HashMaps對他們沒有任何特定的順序。這可能意味着一次迭代它的塊可能無法正確工作,如果它已被修改。如果這確實成爲一個問題,OrderedHashMap將是適當的。 – byxor

+0

@khelwood我確實儘可能地修復了它 – PHA

回答

1

你可以保留一個計數器,初始化爲0,並且將每一個項目,同時收集物品正如你看到的那樣(比如說,ArrayList<Map.Entry<InstaWord, List<Integer>>>)。如果計數器(增量後)等於500,則處理整批,將計數器重置爲0並清除集合。

另一種方法是讓計數器控制循環並明確聲明您從中繪製Map.Entry的迭代器。通過這種方式,它可能會更清晰一些。