一次读取地图 N 个键
Read a map N keys at a time
我有一张地图 (instaWords),里面填满了数千个单词。我需要一次循环 N 项。这是我的代码。在这段代码中,我需要以 500 个单词为单位读取 instaWords,然后用这些单词执行 "updateInstaPhrases"。有帮助吗?
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();
}
我需要遍历哈希图 'in chunks'(例如每次 500 项)
您可以保留一个计数器,初始化为 0 并为每个项目递增,同时收集您认为合适的项目(例如,ArrayList<Map.Entry<InstaWord, List<Integer>>>
)。如果计数器(递增后)等于 500,处理整批,将计数器重置为 0 并清除集合。
另一种选择是让计数器控制循环并明确声明从中绘制 Map.Entry
的迭代器。这样大概就更清楚是怎么回事了。
我有一张地图 (instaWords),里面填满了数千个单词。我需要一次循环 N 项。这是我的代码。在这段代码中,我需要以 500 个单词为单位读取 instaWords,然后用这些单词执行 "updateInstaPhrases"。有帮助吗?
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();
}
我需要遍历哈希图 'in chunks'(例如每次 500 项)
您可以保留一个计数器,初始化为 0 并为每个项目递增,同时收集您认为合适的项目(例如,ArrayList<Map.Entry<InstaWord, List<Integer>>>
)。如果计数器(递增后)等于 500,处理整批,将计数器重置为 0 并清除集合。
另一种选择是让计数器控制循环并明确声明从中绘制 Map.Entry
的迭代器。这样大概就更清楚是怎么回事了。