方法一 在for-each循环中使用entries来遍历 (General)
Map<Integer, Integer> map = new HashMap<Integer, Integer>();
for (Map.Entry<Integer, Integer> entry : map.entrySet()) {
System.out.println("Key = " + entry.getKey() + ", Value = " + entry.getValue());
}
方法二 在for-each循环中遍历keys或values。
如果只需要map中的键或者值,你可以通过keySet或values来实现遍历,而不是用entrySet。
Map<Integer, Integer> map = new HashMap<Integer, Integer>();
//遍历map中的键
for (Integer key : map.keySet()) {
System.out.println("Key = " + key);
}
//遍历map中的值
for (Integer value : map.values()) {
System.out.println("Value = " + value);
}
方法三使用Iterator遍历
使用泛型:
Map<Integer, Integer> map = new HashMap<Integer, Integer>();
Iterator<Map.Entry<Integer, Integer>> entries = map.entrySet().iterator();
while (entries.hasNext()) {
Map.Entry<Integer, Integer> entry = entries.next();
System.out.println("Key = " + entry.getKey() + ", Value = " + entry.getValue());
}
List<Integer> result = new ArrayList<Integer>();
int length = L.length * L[0].length();
int tokenLength = L[0].length();
int tokenCount = L.length;
//put all the words in L into HashMap
Map<String, Integer> map = new HashMap<String, Integer>();
for (String str : L) {
if (!map.containsKey(str)) {
map.put(str, 1);
} else {
map.put(str, str.get(str) + 1);
}
}
//Search in S
for (int i = 0; i < S.length() - length + 1; i++) {
String str = S.substring(i, i+length);
boolean flag = true;
//adding all the worlds in str into the tempHashMap
HashMap<String, Integer> tempMap = new HashMap<String, Integer>();
for (int j=0; j<tokenCount; j++) {
String token = str.substring(j*tokenLength, (j+1)*tokenLength);
if (!map.containsKey(token)) {
flag = false;
break
} else {
if (!tempMap.containsKey(token)) {
tempMap.put(token, 1);
} else {
tempMap.put(token, tempMap.get(token) + 1);
}
}
}
if (!flag) continue;
boolean add = true;
for (Map.Entry<String,Integer> entry : map.entrySet()) {
if (tempMap.get(entry.getKey()) != entry.getValue()) {
add = false;
break;
}
}
if (add) result.add(i);
}
return result;
}
No comments:
Post a Comment