jdk8 Collectors.toMap

示例

import com.jiuqi.bi.util.StringUtils;

import java.util.*;
import java.util.stream.Collectors;

/**
 * @title: CollectorsToMap
 * @Author: 相思子
 * @Date: 2021/9/25 10:02
 * @Description:
 */
public class CollectorsToMap {

    private String id;
    private String code;
    private String title;
    private Integer age;

    public static void main(String[] args) {
        List<CollectorsToMap> list = new ArrayList<>(
                Arrays.asList(
                        new CollectorsToMap("u1", null, "t1",2),
                        new CollectorsToMap("u2", "c2", null,2),
                        new CollectorsToMap("u2", "c1", "t1",2),
                        new CollectorsToMap("", "", "",0),
                        new CollectorsToMap(null, null, null,null),
                        null
                )
        );
        //将list转为以{key:id,value:code}的LinkedHashMap,如果key重复,则以旧数据为准,如果value为null,则赋值为c
        Map<String, String> map = list.stream().filter(item -> item != null && StringUtils.isNotEmpty(item.getId())).collect(Collectors.toMap(item -> item.getId(), item -> Optional.ofNullable(item.getCode()).orElse("c"), (oldVal, currVal) -> oldVal, LinkedHashMap::new));
        System.out.println(map.getClass());
        System.out.println(map.toString());
        //将list转为以{key:id,value:code}的HashMap,如果key重复,则以新数据为准,如果value为null,则赋值为c
        Map<String, String> map0 = list.stream().filter(item -> item != null && StringUtils.isNotEmpty(item.getId())).collect(Collectors.toMap(item -> item.getId(), item -> Optional.ofNullable(item.getCode()).orElse("c"), (oldVal, currVal) -> currVal));
        System.out.println(map0.getClass());
        System.out.println(map0.toString());
        //将list转为以{key:age,value:title}的HashMap,如果key重复,则以旧数据+新数据为value,如果value为null,则赋值为t
        Map<Integer, String> map1 = list.stream().filter(item -> item != null && item.getAge() != null).collect(Collectors.toMap(CollectorsToMap::getAge, item->Optional.ofNullable(item.getTitle()).orElse("t"), (oldVal, currVal) -> oldVal+","+currVal));
        System.out.println(map0.getClass());
        System.out.println(map1.toString());


    }

    @Override
    public String toString() {
        return "CollectorsToMap{" +
                "id='" + id + '\'' +
                ", code='" + code + '\'' +
                ", title='" + title + '\'' +
                ", age=" + age +
                '}';
    }

    public CollectorsToMap(String id, String code, String title, Integer age) {
        this.id = id;
        this.code = code;
        this.title = title;
        this.age = age;
    }

    public String getId() {
        return id;
    }

    public void setId(String id) {
        this.id = id;
    }

    public String getCode() {
        return code;
    }

    public void setCode(String code) {
        this.code = code;
    }

    public String getTitle() {
        return title;
    }

    public void setTitle(String title) {
        this.title = title;
    }

    public Integer getAge() {
        return age;
    }

    public void setAge(Integer age) {
        this.age = age;
    }
}

源码

public static <T, K, U, M extends Map<K, U>>
    Collector<T, ?, M> toMap(Function<? super T, ? extends K> keyMapper,
                                Function<? super T, ? extends U> valueMapper,
                                BinaryOperator<U> mergeFunction,
                                Supplier<M> mapSupplier) {
        BiConsumer<M, T> accumulator
                = (map, element) -> map.merge(keyMapper.apply(element),
                                              valueMapper.apply(element), mergeFunction);
        return new CollectorImpl<>(mapSupplier, accumulator, mapMerger(mergeFunction), CH_ID);
    }

   default V merge(K key, V value,
            BiFunction<? super V, ? super V, ? extends V> remappingFunction) {
        Objects.requireNonNull(remappingFunction);
        //判空,如果value为null,这里会直接抛异常
        Objects.requireNonNull(value);
        V oldValue = get(key);
        V newValue = (oldValue == null) ? value :
                   remappingFunction.apply(oldValue, value);
        if(newValue == null) {
            remove(key);
        } else {
            put(key, newValue);
        }
        return newValue;
    }
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值