如需要將多個集合的中的某一個字段保存到統(tǒng)一集合中。
實體類:
@Data
@Accessors(chain = true)
public static class User{private String name;
private String id;
}
@Data
@Accessors(chain = true)
public static class Student{private String name;
private String id;
}
場景:假設(shè)我們現(xiàn)在有兩個集合,一個List
一個List
我們需要把里面的name統(tǒng)一保存到一個集合中我們應(yīng)該怎么做呢?
提供一個獲取集合中某個字段的方法
public staticListgetField (Listlist, Functionfunction){if (list == null || list.isEmpty()) { return new ArrayList<>();
}
Listcollect = list.stream().map(v->function.apply(v)).collect(Collectors.toList());
return collect;
}
public static void main(String[] args) {// 準(zhǔn)備測試數(shù)據(jù)
ListuserList = new ArrayList<>(){{ add(new User().setId("id1").setName("user1"));
}};
ListstudentList = new ArrayList<>(){{ add(new Student().setId("id2").setName("student1"));
}};
Listlist= new ArrayList<>();
list.addAll(getField(userList,User::getName));
list.addAll(getField(studentList,Student::getName));
System.out.println(list);
}
輸出->>>>[user1, student1]
如果需要統(tǒng)一保存id,只需要這樣list.addAll(getField(userList,User::getId));
你是否還在尋找穩(wěn)定的海外服務(wù)器提供商?創(chuàng)新互聯(lián)www.cdcxhl.cn海外機房具備T級流量清洗系統(tǒng)配攻擊溯源,準(zhǔn)確流量調(diào)度確保服務(wù)器高可用性,企業(yè)級服務(wù)器適合批量采購,新人活動首月15元起,快前往官網(wǎng)查看詳情吧
本文名稱:java-將多個集合中的不同對象的某個字段保存到同一集合-創(chuàng)新互聯(lián)
轉(zhuǎn)載來于:http://jinyejixie.com/article38/dcihpp.html
成都網(wǎng)站建設(shè)公司_創(chuàng)新互聯(lián),為您提供微信公眾號、搜索引擎優(yōu)化、定制開發(fā)、面包屑導(dǎo)航、網(wǎng)站營銷、網(wǎng)站制作
聲明:本網(wǎng)站發(fā)布的內(nèi)容(圖片、視頻和文字)以用戶投稿、用戶轉(zhuǎn)載內(nèi)容為主,如果涉及侵權(quán)請盡快告知,我們將會在第一時間刪除。文章觀點不代表本網(wǎng)站立場,如需處理請聯(lián)系客服。電話:028-86922220;郵箱:631063699@qq.com。內(nèi)容未經(jīng)允許不得轉(zhuǎn)載,或轉(zhuǎn)載時需注明來源: 創(chuàng)新互聯(lián)
猜你還喜歡下面的內(nèi)容