map.merge() 方法

 

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
package utils;
 
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.extern.slf4j.Slf4j;
 
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;
 
@Slf4j
public class Test extends Person {
 
    public static void main(String[] args) {
        List<Clothes> clothes = Arrays.asList(
                new Clothes("C001", Size.SMALL),
                new Clothes("C002", Size.LARGE),
                new Clothes("C003", Size.LARGE),
                new Clothes("C004", Size.MEDIUM),
                new Clothes("C005", Size.SMALL),
                new Clothes("C006", Size.SMALL));
        System.out.println(countBySize(clothes));
    }
 
    public static Map<Size, Integer> countBySize(List<Clothes> clothes) {
        Map<Size, Integer> map = new EnumMap<>(Size.class);
        for (Clothes c : clothes) {
            Size size = c.getSize();
            /*Integer count = map.get(size);
            if (count != null) {
                map.put(size, count + 1);
            } else {
                map.put(size, 1);
            }*/
            map.merge(size, 1, Integer::sum);
        }
        return map;
    }
 
}
 
enum Size {
    SMALL, MEDIUM, LARGE
}
 
@Data
@AllArgsConstructor
class Clothes {
    String id;
    Size size;
}

  

1
2
3
4
5
6
Integer count = map.get(size);
if (count != null) {
    map.put(size, count + 1);
} else {
    map.put(size, 1);
}

可以替换为

1
map.merge(size, 1, Integer::sum);

该方法接收三个参数,一个 key 值,一个 value,一个 remappingFunction ,如果给定的key不存在,它就变成了 put(key, value) 。

但是,如果 key 已经存在一些值,remappingFunction 可以选择合并的方式,然后将合并得到的 newValue 赋值给原先的 key。

 

posted @   草木物语  阅读(686)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· 震惊!C++程序真的从main开始吗?99%的程序员都答错了
· 【硬核科普】Trae如何「偷看」你的代码?零基础破解AI编程运行原理
· 单元测试从入门到精通
· 上周热点回顾(3.3-3.9)
· winform 绘制太阳,地球,月球 运作规律
点击右上角即可分享
微信分享提示