2016-08-18 44 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的迭代器。通过这种方式,它可能会更清晰一些。