首页 > 其他 > 详细

使用Lambda表达式给对象赋值

时间:2021-04-16 21:41:18      阅读:131      评论:0      收藏:0      [点我收藏+]

使用Lambda表达式给对象赋值

  1. 简化代码

代码演示

  1. 如下
import com.alibaba.fastjson.JSON;

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.stream.Collectors;

public class Test {
    public static void main(String[] args) {

        InfoNoticeItem re2 = new InfoNoticeItem();
        re2.setIds("2");
        re2.setStoreCode("高佳琪");

        InfoNoticeItem re4 = new InfoNoticeItem();
        re4.setIds("4");
        re4.setStoreCode("王莹莹");

        List<InfoNoticeItem> list = new ArrayList<>();
        Collections.addAll(list, re2, re4);

        ShopInfoNoticeReq shopInfoNoticeReq = new ShopInfoNoticeReq();
        shopInfoNoticeReq.setFormat(null);
        shopInfoNoticeReq.setIdList(list);

        // 赋值.setIdList(collect)
        // public void setIdList(List<InfoNoticeItem> idList)
        List<InfoNoticeItem> collect = shopInfoNoticeReq.getIdList().stream().map(item -> {
            InfoNoticeItem ini = new InfoNoticeItem();
            ini.setIds(item.getIds());
            ini.setStoreCode(item.getStoreCode());
            return ini;
        }).collect(Collectors.toList());

        try {
            Thread.sleep(2000);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        System.out.println(JSON.toJSON(collect));
    }
}

输出

  1. 原本格式: [InfoNoticeItem(ids=2, storeCode=高佳琪), InfoNoticeItem(ids=4, storeCode=王莹莹)]
  2. JSON格式后: [{"ids":"2","storeCode":"高佳琪"},{"ids":"4","storeCode":"王莹莹"}]

使用Lambda表达式给对象赋值

原文:https://www.cnblogs.com/Twittery/p/14668293.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!