【JDK8】Map 便利的預設方法
|
JDK8 的 API 有不少便利的預設方法,其中像是 forEach在過去如果要同時迭代 public static void main(String[] args) {
Map<String, String> enChMap = new TreeMap<>();
enChMap.put("one", "一");
enChMap.put("two", "二");
enChMap.put("three", "三");
foreach(enChMap.entrySet());
}
static void foreach(Iterable<Map.Entry<String, String>> iterable) {
for(Map.Entry<String, String> entry: iterable) {
out.printf("(鍵 %s, 值 %s)%n",
entry.getKey(), entry.getValue());
}
}
主要是透過 Map<String, String> enChMap = new TreeMap<>();
enChMap.put("one", "一");
enChMap.put("two", "二");
enChMap.put("three", "三");
enChMap.forEach(
(key, value) -> out.printf("(鍵 %s, 值 %s)%n", key, value)
);
範例中看到的 getOrDefault,putIfAbsent
String ch = enChMap.get(en);
if(ch == null) {
ch = "Unknown";
}
在 JDK8 中可以改為: String ch = enChMap.getOrDefault(en, "Unknown");
V v = map.get(key);
if(v == null) {
v = map.put(key, value);
}
return v;
JDK8 中可以直接改寫為: return map.putIfAbsent(key, value); computeIfAbsent、computeIfPresent、compute有時會想要檢查鍵是否有對應的值,若不存在時將為鍵設定對應的值,這時可以使用 static Map<Integer, Integer> cache = new HashMap<>();
static int primeNumberOf(int nth) {
Integer prime = cache.get(nth);
if(prime == null) {
prime = calculatePrime(nth); // calculatePrime 實際計算第 n 質數
cache.put(nth, prime);
}
return prime;
}
使用 JDK8 的話,你可以改為: static int primeNumberOf(int nth) {
return cache.computeIfAbsent(nth, key -> calculatePrime(key));
}
if(map.get(key) == null) {
V newValue = mappingFunction.apply(key);
if(newValue != null) {
map.put(key, newValue);
}
}
if(map.get(key) != null) {
V oldValue = map.get(key);
V newValue = remappingFunction.apply(key, oldValue);
if(newValue != null) {
map.put(key, newValue);
} else {
map.remove(key);
}
}
compute、merge
map.compute(key, (k, v) -> (v == null) ? msg : v.concat(msg)) 鍵有對應的值時,Lambda 的傳回值若不為 V oldValue = map.get(key);
V newValue = remappingFunction.apply(key, oldValue);
if(oldValue != null ) {
if(newValue != null) {
map.put(key, newValue);
} else {
map.remove(key);
}
} else {
if (newValue != null) {
map.put(key, newValue);
} else {
return null;
}
}
map.merge(key, msg, String::concat)
V oldValue = map.get(key);
V newValue = (oldValue == null) ? value :
remappingFunction.apply(oldValue, value);
if(newValue == null) {
map.remove(key);
} else {
map.put(key, newValue);
}
remove、replace、replaceAll
if(map.containsKey(key) && Objects.equals(map.get(key), value)) {
map.remove(key);
return true;
} else {
return false;
}
類似地, if(map.containsKey(key) && Objects.equals(map.get(key), oldValue)) {
map.put(key, newValue);
return true;
} else {
return false;
}
|

Java 學習之路





