使用Lambda表達式給對象賦值
- 技術點
- 使用Lambda表達式.map循環遍歷List集合賦值
- 實體類
@Data
public class InfoNoticeItem implements Serializable {
/**
* serialVersionUID
*/
private static final long serialVersionUID = 6411598034131994800L;
/**
* ids 商品內碼
*/
private String ids;
/**
* storeCode 門店編號
*/
private String storeCode;
}
- 測試類
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]