JDK8通過Stream 對List,Map操作和互轉(zhuǎn)的實(shí)現(xiàn)
1、Map數(shù)據(jù)轉(zhuǎn)換為自定義對象的List,例如把map的key,value分別對應(yīng)Person對象兩個(gè)屬性:
List<Person> list = map.entrySet().stream().sorted(Comparator.comparing(e -> e.getKey())) .map(e -> new Person(e.getKey(), e.getValue())).collect(Collectors.toList()); List<Person> list = map.entrySet().stream().sorted(Comparator.comparing(Map.Entry::getValue)) .map(e -> new Person(e.getKey(), e.getValue())).collect(Collectors.toList()); List<Person> list = map.entrySet().stream().sorted(Map.Entry.comparingByKey()) .map(e -> new Person(e.getKey(), e.getValue())).collect(Collectors.toList());
以上三種方式不同之處在于排序的處理。參考鏈接:
https://www.concretepage.com/java/jdk-8/java-8-convert-map-to-list-using-collectors-tolist-example
2、List對象轉(zhuǎn)換為其他List對象:
List<Employee> employees = persons.stream()
.filter(p -> p.getLastName().equals("l1"))
.map(p -> new Employee(p.getName(), p.getLastName(), 1000))
.collect(Collectors.toList());
3、從List中過濾出一個(gè)元素
User match = users.stream().filter((user) -> user.getId() == 1).findAny().get();
4、List轉(zhuǎn)換為Map
public class Hosting {
private int Id;
private String name;
private long websites;
public Hosting(int id, String name, long websites) {
Id = id;
this.name = name;
this.websites = websites;
}
//getters, setters and toString()
}
Map<Integer, String> result1 = list.stream().collect(
Collectors.toMap(Hosting::getId, Hosting::getName));
以上就是本文的全部內(nèi)容,希望對大家的學(xué)習(xí)有所幫助,也希望大家多多支持腳本之家。
- 詳解Java8新特性Stream之list轉(zhuǎn)map及問題解決
- Java8 實(shí)現(xiàn)stream將對象集合list中抽取屬性集合轉(zhuǎn)化為map或list
- java8 Stream list to Map key 重復(fù) value合并到Collectio的操作
- 解決使用stream將list轉(zhuǎn)map時(shí),key重復(fù)導(dǎo)致報(bào)錯(cuò)的問題
- Java8 中使用Stream 讓List 轉(zhuǎn) Map使用問題小結(jié)
- 關(guān)于List、Map、Stream初始化方式
- Java中List使用stream流轉(zhuǎn)成map的幾種方式詳解
相關(guān)文章
springboot帶有進(jìn)度條的上傳功能完整實(shí)例
這篇文章主要介紹了springboot帶有進(jìn)度條的上傳功能,結(jié)合完整實(shí)例形式分析了springboot帶進(jìn)度條上傳的原理、實(shí)現(xiàn)步驟與相關(guān)操作技巧,需要的朋友可以參考下2019-11-11
SpringBoot JPA實(shí)現(xiàn)查詢多值
這篇文章主要為大家詳細(xì)介紹了SpringBoot JPA實(shí)現(xiàn)查詢多值,文中示例代碼介紹的非常詳細(xì),具有一定的參考價(jià)值,感興趣的小伙伴們可以參考一下2018-08-08
關(guān)于Spring Bean實(shí)例過程中使用反射和遞歸處理的Bean屬性填充問題
本文帶領(lǐng)大家一起學(xué)習(xí)下在Spring Bean實(shí)例過程中如何使用反射和遞歸處理的Bean屬性填充,需要在類 AbstractAutowireCapableBeanFactory 的 createBean 方法中添加補(bǔ)全屬性方法,具體操作方法跟隨小編一起學(xué)習(xí)下吧2021-06-06
解決IDEA開發(fā)工具右側(cè)沒有Maven工具欄的問題
這篇文章主要給大家解決了IDEA開發(fā)工具右側(cè)沒有Maven工具欄的問題,文中有詳細(xì)的解決步驟,如果有遇到一樣問題的小伙伴,可以參考閱讀本文2023-09-09
Java實(shí)現(xiàn)轉(zhuǎn)換圖片格式的示例代碼
在日常的軟件開發(fā)中,處理圖像文件是一項(xiàng)常見任務(wù),這篇文章將實(shí)現(xiàn)實(shí)現(xiàn)一個(gè)簡單的Java程序,用于將一種圖片格式轉(zhuǎn)換為另一種格式,需要的可以了解下2025-02-02

