ComputeIfPresent
import java.util.HashMap;
import java.util.Map;
import java.util.Objects;
import java.util.function.BiFunction;
public class MapComputeIfPresentTest {
public static void main(String[] args) {
mappdingFunctionThrowException();
}
private static void computeIfPresent() {
Map<Integer, String> cityMap = new HashMap<>();
cityMap.put(101, "Varanasi");
cityMap.put(102, "Prayag");
// 如果get(k)不为null,就将(k,v) -> {}结果替换get(k)的值,如果(k,v) -> {}返回null,则移除remove(k)
String newValue = cityMap.computeIfPresent(102, (k, v) -> v != null ? v.concat("raj") : null);
System.out.println(newValue);
System.out.println(cityMap);
}
private static void equivalentWayOfComputeIfPresent() {
Map<Integer, String> cityMap = new HashMap<>();
cityMap.put(101, "Varanasi");
cityMap.put(102, "Prayag");
BiFunction<Integer,String, String> biFunction = (k,v) -> v != null ? v.concat("raj") : null;
int key = 102;
String oldValue = cityMap.get(key);
String newValue = biFunction.apply(key, oldValue);
if (Objects.nonNull(cityMap.get(102))){
if (Objects.nonNull(newValue)){
cityMap.put(key, newValue);
}else {
cityMap.remove(key);
}
}
System.out.println(newValue);
System.out.println(cityMap);
}
private static void odlValueNotNullAndNewValueNull() {
Map<Integer, String> cityMap = new HashMap<>();
cityMap.put(101, "Varanasi");
cityMap.put(102, "Prayag");
// get(102) !=null 但是 (k, v) ->{} 返回null, 所以删除remove(k)
cityMap.computeIfPresent(102, (k, v) -> null);
System.out.println(cityMap);
}
private static void oldValueNullAndNewValueNotNull() {
Map<Integer, String> cityMap = new HashMap<>();
cityMap.put(101, "Varanasi");
cityMap.put(102, null);
// get(102) == null,不做任何修改
cityMap.computeIfPresent(102, (k, v) -> "Noida");
System.out.println(cityMap);
}
private static void mappdingFunctionThrowException() {
Map<Integer, String> cityMap = new HashMap<>();
cityMap.put(101, "Varanasi");
cityMap.put(102, "Noida");
String newVal = null;
try {
// (k, v) -> {} 抛异常,cityMap不做任何修改
cityMap.computeIfPresent(102, (k, v) -> newVal.concat("Prayag")); //throws exception
} catch (Throwable e) {
System.out.println(e);
}
System.out.println(cityMap);
}
}
ComputeIfAbsent
import java.util.HashMap;
import java.util.Map;
import java.util.Objects;
import java.util.function.Function;
public class MapComputeIfAbsent {
public static void main(String[] args) {
computeIfAbsent();
}
private static void computeIfAbsent() {
Map<Integer, String> cityMap = new HashMap<>();
cityMap.put(101, "Varanasi");
cityMap.put(102, "Prayag");
// 如果key不存在,且k ->{}不为null, 则添加key, k ->{}到map
String value = cityMap.computeIfAbsent(103, k -> "Noida");
System.out.println(value);
System.out.println(cityMap);
}
private static void equivalentWayOfComputeIfAbsent() {
// computeIfAbsent的底层逻辑
Map<Integer, String> cityMap = new HashMap<>();
cityMap.put(101, "Varanasi");
cityMap.put(102, "Prayag");
int key = 103;
Function<Integer, String> function = k -> "Noida";
String applyNewValue = function.apply(key);
if (Objects.isNull(cityMap.get(key))){
if (Objects.nonNull(applyNewValue)){
cityMap.put(key, applyNewValue);
}
}
System.out.println(applyNewValue);
System.out.println(cityMap);
}
private static void keyNotExistButNewValueIsNull() {
Map<Integer, String> cityMap = new HashMap<>();
cityMap.put(101, "Varanasi");
cityMap.put(102, "Prayag");
cityMap.computeIfAbsent(103, k -> null);
System.out.println(cityMap);
}
private static void keyAssociatedNotNullValue() {
Map<Integer, String> cityMap = new HashMap<>();
cityMap.put(101, "Varanasi");
cityMap.put(102, "Prayag");
cityMap.computeIfAbsent(102, k -> "Noida");
System.out.println(cityMap);
}
private static void keyAssociatedNullValue() {
Map<Integer, String> cityMap = new HashMap<>();
cityMap.put(101, "Varanasi");
cityMap.put(102, null);
cityMap.computeIfAbsent(102, k -> "Prayagraj");
System.out.println(cityMap);
}
}
Compute
import java.util.HashMap;
import java.util.Map;
import java.util.function.BiFunction;
public class MapComputeTest {
public static void main(String[] args) {
equivalentWayOfCompute();
}
private static void equivalentWayOfCompute() {
Map<Integer, String> studentMap = new HashMap<>();
studentMap.put(101, "Mahesh");
studentMap.put(102, "Suresh");
BiFunction<Integer, String, String> remappingFunction = (k, v) -> v + "-" + k;
int key = 101;
String oldValue = studentMap.get(key);
String newValue = remappingFunction.apply(key, oldValue);
if (oldValue != null) {
if (newValue != null)
studentMap.put(key, newValue);
else
studentMap.remove(key);
} else {
if (newValue != null)
studentMap.put(key, newValue);
else
studentMap.remove(key);
}
System.out.println(newValue);
System.out.println(studentMap);
}
private static void compute() {
Map<Integer, String> studentMap = new HashMap<>();
studentMap.put(101, "Mahesh");
studentMap.put(102, "Suresh");
studentMap.put(105, null);
// get(key) == null 且 (k,v)!=null, 添加键值对或覆盖value
studentMap.compute(103, (k,v) -> "Davida");
System.out.println(studentMap);
// get(key) != null 且 (k,v)!=null,覆盖原来的value
studentMap.compute(102, (k,v) ->"Suresh2");
System.out.println(studentMap);
// get(key) != null 且 (k,v)==null, 删除键值对
studentMap.compute(103, (k,v) -> null);
System.out.println(studentMap);
// get(key) == null 且 (k,v)==null, 删除键值对
studentMap.compute(105, (k,v) -> null);
System.out.println(studentMap);
}
}
Replace
import java.util.HashMap;
import java.util.Map;
public class MapReplaceTest {
public static void main(String[] args) {
Map<Integer, String> studentMap = new HashMap<>();
studentMap.put(101, "Mahesh");
studentMap.put(102, "Suresh");
studentMap.put(103, "Krishna");
// key对应的value不为null,替换value并返回value
String oldValue = studentMap.replace(101, "Mr.Mahesh");
System.out.println(studentMap);
System.out.println(oldValue);
// key对应的value为null, 返回null,studentMap不做任何操作
String keyNotAssociateValue = studentMap.replace(105, "Davida");
System.out.println(studentMap);
System.out.println(keyNotAssociateValue);
// get(key) == oldValue,则将newValue覆盖原来的value并返回true
boolean isReplaced = studentMap.replace(102, "Suresh", "Mr.Suresh");
System.out.println(studentMap);
System.out.println(isReplaced);
// get(key) != oldValue,不做任何操作并返回false
isReplaced = studentMap.replace(103, "Krishna11", "Mr.Krishna");
System.out.println(studentMap);
System.out.println(isReplaced);
}
}
RelaceAll
Map<Integer, String> studentMap = new HashMap<>();
studentMap.put(101, "Mahesh");
studentMap.put(102, "Suresh");
studentMap.put(103, "Krishna");
System.out.println("--- before replaceAll() ---");
System.out.println(studentMap);
studentMap.replaceAll((k, v) -> {
if (k > 101){
v = v + "-" + k;
}
return v;
});
System.out.println("--- after replaceAll() ---");
System.out.println(studentMap);
GetOrDefault
Map<Integer, String> studentMap = new HashMap<>();
studentMap.put(101, "Mahesh");
studentMap.put(102, "Suresh");
studentMap.put(103, "Krishna");
String no_student = studentMap.getOrDefault(104, "no student");
System.out.println(studentMap);
System.out.println(no_student);
String no_student2 = studentMap.getOrDefault(102, "no student");
System.out.println(studentMap);
System.out.println(no_student2);
Merge
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.function.BiFunction;
public class MapMergeTest {
public static void main(String[] args) {
exampleOfMerge();
}
private static void exampleOfMerge() {
List<StudentScore> list = new ArrayList<>();
list.add(new StudentScore(1, "chinese", 110));
list.add(new StudentScore(1, "english", 120));
list.add(new StudentScore(1, "math", 135));
list.add(new StudentScore(2, "chinese", 99));
list.add(new StudentScore(2, "english", 100));
list.add(new StudentScore(2, "math", 133));
list.add(new StudentScore(3, "chinese", 88));
list.add(new StudentScore(3, "english", 140));
list.add(new StudentScore(3, "math", 90));
list.add(new StudentScore(4, "chinese", 108));
list.add(new StudentScore(4, "english", 123));
list.add(new StudentScore(4, "math", 114));
list.add(new StudentScore(5, "chinese", 116));
list.add(new StudentScore(5, "english", 133));
list.add(new StudentScore(5, "math", 135));
// 统计学生的总成绩
System.out.println(sum1(list));
System.out.println(sum2(list));
}
//传统写法
public static Map<Integer, Integer> sum1(List<StudentScore> list) {
Map<Integer, Integer> map = new HashMap<>();
for (StudentScore studentScore : list) {
if (map.containsKey(studentScore.getSid())) {
map.put(studentScore.getSid(),
map.get(studentScore.getSid()) + studentScore.getScore());
} else {
map.put(studentScore.getSid(), studentScore.getScore());
}
}
return map;
}
//merger写法
public static Map<Integer, Integer> sum2(List<StudentScore> list) {
Map<Integer, Integer> map = new HashMap<>();
list.stream().forEach(studentScore -> map.merge(studentScore.getSid()
, studentScore.getScore(), Integer::sum));
return map;
}
private static void merge() {
Map<Integer, String> studentMap = new HashMap<>();
studentMap.put(101, "Mahesh");
studentMap.put(102, "Suresh");
studentMap.put(103, "Krishna");
// key(104)未关联任何value,添加键值对key-value. 104-David
studentMap.merge(104,"David", (k,v) -> "SuSan");
System.out.println(studentMap);
// key(103)已关联value,取BiFunction结果覆盖value
studentMap.merge(103, "Mr.Krishna", String::concat);
System.out.println(studentMap);
// key(103)已关联value,BiFunction返回结果为null,删除remove(103)
studentMap.merge(103, "Mr.Krishna", (k,v) -> null);
System.out.println(studentMap);
}
private static void equivalentWayOfMerge() {
Map<Integer, String> studentMap = new HashMap<>();
studentMap.put(101, "Mahesh");
studentMap.put(102, "Suresh");
studentMap.put(103, "Krishna");
int key = 103;
String value = studentMap.get(key);
BiFunction<String, String, String> remappingFunction = (oldValue, newValue) -> oldValue.concat(newValue);
String newValue = "Mr.Krishna";
newValue = (value == null) ? newValue :remappingFunction.apply(value, newValue);
if (newValue == null)
studentMap.remove(key);
else
studentMap.put(key, newValue);
System.out.println(studentMap);
}
static class StudentScore {
private Integer sid;
private String scoreName;
private Integer score;
public StudentScore(Integer sid, String scoreName, Integer score) {
this.sid = sid;
this.scoreName = scoreName;
this.score = score;
}
public StudentScore() {
}
public Integer getSid() {
return sid;
}
public void setSid(Integer sid) {
this.sid = sid;
}
public String getScoreName() {
return scoreName;
}
public void setScoreName(String scoreName) {
this.scoreName = scoreName;
}
public Integer getScore() {
return score;
}
public void setScore(Integer score) {
this.score = score;
}
}
}