这个问题已经回答。我花了一些时间来理解(“如果映射已经包含了computeIfAbsent中指定键的值,则不需要执行昂贵的操作”),我在这里加了我的理解。希望这对其他人有帮助:
putIfAbsent()
行为就像put()
地图已经包含指定键的值时一样。putIfAbsent()
仅检查key是否为null。如果它不为null,则返回该值,然后map再次获取该值。
但是,computeIfAbsent()
对于键和值都没有null检查。在对值进行null检查期间,如果它不为null,则将来自映射对象的现有值分配给newValue并将其返回。这就是为什么不需要重新获取值的原因,因为重复使用了map中的现有值。
请参考以下程序以供参考:
public class MapTest1 {
public static final String AJAY_DEVGAN = "Ajay Devgn";
public static final String AUTOBIOGRAPHY = "Autobiography";
public static void main(String[] args) {
MapTest1 mt = new MapTest1();
mt.testPutCompute();
}
private void testPutCompute() {
Map<String, List<String>> movies = getMovieObject();
System.out.println("\nCalling putIfAbsent method.....");
movies.putIfAbsent(AJAY_DEVGAN, getAjayDevgnMovies());
System.out.println("\nCalling computeIfAbsent method......");
movies.computeIfAbsent(AUTOBIOGRAPHY, t -> getAutobiographyMovies());
}
private Map<String, List<String>> getMovieObject() {
Map<String, List<String>> movies = new HashMap<>();
movies.put(AJAY_DEVGAN, getAjayDevgnMovies());
movies.put(AUTOBIOGRAPHY, getAutobiographyMovies());
System.out.println(movies);
return movies;
}
private List<String> getAutobiographyMovies() {
System.out.println("Getting autobiography movies");
List<String> list = new ArrayList<>();
list.add("M.S. Dhoni - The Untold Story");
list.add("Sachin: A Billion Dreams");
return list;
}
private List<String> getAjayDevgnMovies() {
System.out.println("Getting Ajay Devgn Movies");
List<String> ajayDevgnMovies = new ArrayList<>();
ajayDevgnMovies.add("Jigar");
ajayDevgnMovies.add("Pyar To Hona Hi Tha");
return ajayDevgnMovies;
}
}
请参阅以下代码以获取接口putIfAbsent()
和computeIfAbsent()
来自接口Map.class
public interface Map<K,V> {
.....
default V putIfAbsent(K key, V value) {
V v = get(key);
if (v == null) {
v = put(key, value);
}
return v;
}
default V computeIfAbsent(K key,
Function<? super K, ? extends V> mappingFunction) {
Objects.requireNonNull(mappingFunction);
V v;
if ((v = get(key)) == null) {
V newValue;
if ((newValue = mappingFunction.apply(key)) != null) {
put(key, newValue);
return newValue;
}
}
return v;
}
.........
}