【MapSheep】
[好记性不如烂笔头]
posts - 228,comments - 15,views - 17万

使用Lambda表达式给对象赋值

  1. 技术点
  • 使用Lambda表达式.map循环遍历List集合赋值
  1. 实体类
@Data
public class InfoNoticeItem implements Serializable {
/**
* serialVersionUID
*/
private static final long serialVersionUID = 6411598034131994800L;
/**
* ids 商品内码
*/
private String ids;
/**
* storeCode 门店编号
*/
private String storeCode;
}

  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));
//TODO 输出:[{"ids":"2","storeCode":"高佳琪"},{"ids":"4","storeCode":"王莹莹"}]
}
}

简单使用

ArrayList<Student> list = new ArrayList<>();
Collections.addAll(list, new Student(0, "张三"), new Student(10, "李四"));
System.out.println(list.stream().map(value -> value.getId()).collect(Collectors.toList()));
System.out.println(list.stream().map(Student::getId).collect(Collectors.toList()));
//输出: [0, 10]
//输出: [0, 10]
posted on   (Play)  阅读(5073)  评论(0编辑  收藏  举报
编辑推荐:
· 从 HTTP 原因短语缺失研究 HTTP/2 和 HTTP/3 的设计差异
· AI与.NET技术实操系列:向量存储与相似性搜索在 .NET 中的实现
· 基于Microsoft.Extensions.AI核心库实现RAG应用
· Linux系列:如何用heaptrack跟踪.NET程序的非托管内存泄露
· 开发者必知的日志记录最佳实践
阅读排行:
· TypeScript + Deepseek 打造卜卦网站:技术与玄学的结合
· Manus的开源复刻OpenManus初探
· AI 智能体引爆开源社区「GitHub 热点速览」
· 从HTTP原因短语缺失研究HTTP/2和HTTP/3的设计差异
· 三行代码完成国际化适配,妙~啊~

点击右上角即可分享
微信分享提示