map.merge() 方法

 

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;
}

  

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

可以替换为

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

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

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

 

posted @ 2022-09-22 15:39  草木物语  阅读(703)  评论(0)    收藏  举报