java8stream将list对象{id:““,name:““,nickName:““}转为map,id为key,name为value,name值没有就取nickName

该代码示例展示了如何使用Java8的StreamAPI和Collectors.toMap方法将包含Person对象的List转换为Map,其中Person的id作为键,name或nickName(当name为空时)作为值。
摘要由CSDN通过智能技术生成

要使用Java 8 Stream将List对象转换为Map,其中id作为键(key),name作为值(value),如果name不存在,则使用nickName作为值,可以使用以下代码实现:

import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

public class ListToMapConversion {
    public static void main(String[] args) {
        List<Person> personList = List.of(
                new Person("1", "John", "Johnny"),
                new Person("2", "", "Mike"),
                new Person("3", "Alice", "")
        );

        Map<String, String> resultMap = personList.stream()
                .collect(Collectors.toMap(
                        Person::getId,
                        person -> person.getName().isEmpty() ? person.getNickName() : person.getName(),
                        (existingValue, newValue) -> existingValue, // 如果有重复的键,保留旧值
                        HashMap::new // 指定返回的Map类型
                ));

        System.out.println(resultMap);
    }

    static class Person {
        private String id;
        private String name;
        private String nickName;

        public Person(String id, String name, String nickName) {
            this.id = id;
            this.name = name;
            this.nickName = nickName;
        }

        public String getId() {
            return id;
        }

        public String getName() {
            return name;
        }

        public String getNickName() {
            return nickName;
        }
    }
}

在上述代码中,我们使用了一个自定义的Person类来表示列表中的对象,其中包含id、name和nickName字段。通过Java 8的Stream API和Collectors.toMap方法,我们将List转换为一个Map<String, String>,其中id是键,name是值,如果name为空,则使用nickName作为值。

输出结果将会是:{1=John, 2=Mike, 3=Alice}

请根据实际情况修改Person类和输入的List对象,以适应你的需求。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值