package com.enterprise.map;
import com.google.common.collect.Lists;
import com.google.common.collect.Maps;
import lombok.extern.slf4j.Slf4j;
import java.util.List;
import java.util.Map;
/**
* 如果map中KEY=1存在,返回test方法的值,并覆盖KEY=1对应的VALUE,如果KEY不存在,就把KEY=1对应的默认VALUE的值赋值为1
* map.merge(KEY,defaultValue,test())
* map1.merge("1", 1, MapMerge::test);
*/
@Slf4j
public class MapMerge {
public static void main(String[] args) {
Map<String, Object> map1 = Maps.newHashMap();
map1.put("1", 1);
map1.put("2", 2);
Map<String, Object> map2 = Maps.newHashMap();
map1.put("1", 1);
map1.put("2", 2);
// 如果KEY存在,返回test方法的值,并覆盖KEY对应的VALUE,如果KEY不存在,就把KEY对应的VALUE的值赋值为1
map1.merge("1", 1, MapMerge::test);
log.info("\n" + map1);
}
private static Object test(Object o, Object o1) {
return null;
}
private static void testComputer() {
Map<Object, Integer> map = Maps.newHashMap();
List<Long> words = Lists.newArrayList(1L, 2L);
words.forEach(word -> {
map.compute(3, MapMerge::test2);
});
log.info("\n" + map);
}
public static Integer test2(Object o, Integer integer) {
return 1;
}
public static void computerTest() {
Map<Object, Integer> map = Maps.newHashMap();
List<Long> words = Lists.newArrayList(1L, 2L);
words.forEach(word -> {
/**
* compute方法主要做了三件事:
* 1. 获取map中key=word的数据,test2的参数为:key=word,value=get(word),value有可能是null
* 2. 经过test2方法的执行返回一个value2
* 3. put(word,value2)
*/
map.compute(word, MapMerge::test2);
});
log.info("\n" + map);
}
}
2.Map-merge方法
最新推荐文章于 2024-04-30 16:36:08 发布