MyNumber类
public class MyNumber {
private Long id;
private BigDecimal num;
public MyNumber() {
}
public MyNumber(Long id, BigDecimal num) {
this.id = id;
this.num = num;
}
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public BigDecimal getNum() {
return num;
}
public void setNum(BigDecimal num) {
this.num = num;
}
@Override
public String toString() {
return "MyNumber{" +
"id=" + id +
", num=" + num +
'}';
}
}
测试类:
package map;
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
public class MapTest02 {
public static List<MyNumber> list = new ArrayList<>();
static {
list.add(new MyNumber(1L, new BigDecimal("111")));
list.add(new MyNumber(2L, new BigDecimal("222")));
list.add(new MyNumber(3L, new BigDecimal("333")));
}
public static void main(String[] args) {
HashMap<Long, BigDecimal> map = new HashMap<>();
map.put(1L, new BigDecimal("200"));
map.put(2L, new BigDecimal("300"));
map.putIfAbsent(1L, new BigDecimal("900"));
System.out.println("+++++++++++++++++putIfAbsent++++++++++++++++");
System.out.println(map);
map.computeIfAbsent(5L, k -> {
System.out.println(k);
for (MyNumber number : list) {
if (number.getNum().equals(new BigDecimal("111"))) {
return number.getNum();
}
}
return BigDecimal.ZERO;
});
System.out.println("+++++++++++++++++computeIfAbsent++++++++++++++++");
System.out.println(map);
map.computeIfPresent(5L, (k, v) -> {
System.out.println(k);
System.out.println(v);
for (MyNumber number : list) {
if (number.getNum().equals(new BigDecimal("222"))) {
return number.getNum();
}
}
return BigDecimal.ZERO;
});
System.out.println("+++++++++++++++++computeIfPresent++++++++++++++++");
System.out.println(map);
}
}
输出:
+++++++++++++++++putIfAbsent++++++++++++++++
{1=200, 2=300}
5
+++++++++++++++++computeIfAbsent++++++++++++++++
{1=200, 2=300, 5=111}
5
111
+++++++++++++++++computeIfPresent++++++++++++++++
{1=200, 2=300, 5=222}