java putifabsent_Java 8 Map中的putIfAbsent和computeIfAbsent有什么区别?

这个问题已经回答。 我花了一些时间来理解(“如果映射已经包含了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;

}

.........

}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值