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;
    }
}
Collectors.toMap()是JDK8中提供的一个方法,用于将Stream流转换为Map。它可以根据某一属性,对对象的实例或属性进行映射。通过使用Collectors.toMap(),我们可以方便地将Stream中的元素映射为一个Map。 为了处理可能出现的空指针异常,推荐使用如下方式来使用Collectors.toMap()方法: ```java Map<String, Integer> nameMap = list.stream() .collect(Collectors.toMap(User::getName, o -> Optional.ofNullable(o.getAge()).orElse(-1), (v1, v2) -> v1)); ``` 上述代码中,我们使用了User对象的name属性作为Map的key,使用User对象的age属性作为Map的value。在处理value的过程中,我们使用Optional.ofNullable()方法来处理可能为空的情况,并且使用orElse()方法指定了一个默认值。在多个元素映射到同一个key时,我们使用了一个合并函数来决定保留哪个value值。 这种处理方式能够避免空指针异常的出现,因为在底层的HashMap.merge()方法中会对value进行非空判断。如果遇到空值,则会使用合并函数来处理。<span class="em">1</span><span class="em">2</span><span class="em">3</span> #### 引用[.reference_title] - *1* *2* *3* [Java8 Collectors.toMap() 的使用](https://blog.csdn.net/qq_33204709/article/details/128058684)[target="_blank" data-report-click={"spm":"1018.2226.3001.9630","extra":{"utm_source":"vip_chatgpt_common_search_pc_result","utm_medium":"distribute.pc_search_result.none-task-cask-2~all~insert_cask~default-1-null.142^v93^chatsearchT3_1"}}] [.reference_item style="max-width: 100%"] [ .reference_list ]
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值