这个问题已经回答。 我花了一些时间来理解(“如果映射已经包含了computeIfAbsent中指定键的值,则不需要执行昂贵的操作”)我把我的理解这里。 希望这对其他人有帮助:
当map已经包含指定键的值时,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> movies = getMovieObject();
System.out.println("\nCalling putIfAbsent method.....");
//System.out.println(movies.get(AJAY_DEVGAN));
//movies.put(AJAY_DEVGAN, getAjayDevgnMovies());
movies.putIfAbsent(AJAY_DEVGAN, getAjayDevgnMovies());
System.out.println("\nCalling computeIfAbsent method......");
//System.out.println(movies.get(AUTOBIOGRAPHY));
movies.computeIfAbsent(AUTOBIOGRAPHY, t -> getAutobiographyMovies());
}
private Map> getMovieObject() {
Map> movies = new HashMap<>();
movies.put(AJAY_DEVGAN, getAjayDevgnMovies());
movies.put(AUTOBIOGRAPHY, getAutobiographyMovies());
System.out.println(movies);
return movies;
}
private List getAutobiographyMovies() {
System.out.println("Getting autobiography movies");
List list = new ArrayList<>();
list.add("M.S. Dhoni - The Untold Story");
list.add("Sachin: A Billion Dreams");
return list;
}
private List getAjayDevgnMovies() {
System.out.println("Getting Ajay Devgn Movies");
List ajayDevgnMovies = new ArrayList<>();
ajayDevgnMovies.add("Jigar");
ajayDevgnMovies.add("Pyar To Hona Hi Tha");
return ajayDevgnMovies;
}
}
请参阅下面的代码,以获取接口Map.class中的putIfAbsent()和computeIfAbsent()
public interface Map {
.....
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;
}
.........
}