JDK8通過Stream 對List,Map操作和互轉(zhuǎn)的實現(xiàn)
1、Map數(shù)據(jù)轉(zhuǎn)換為自定義對象的List,例如把map的key,value分別對應(yīng)Person對象兩個屬性:
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中過濾出一個元素
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 實現(xiàn)stream將對象集合list中抽取屬性集合轉(zhuǎn)化為map或list
- java8 Stream list to Map key 重復(fù) value合并到Collectio的操作
- 解決使用stream將list轉(zhuǎn)map時,key重復(fù)導(dǎo)致報錯的問題
- Java8 中使用Stream 讓List 轉(zhuǎn) Map使用問題小結(jié)
- 關(guān)于List、Map、Stream初始化方式
- Java中List使用stream流轉(zhuǎn)成map的幾種方式詳解
相關(guān)文章
SpringBoot中yml多環(huán)境配置的3種方法
這篇文章主要給大家介紹了SpringBoot中yml多環(huán)境配置的3種方法,文中有詳細(xì)的代碼示例供大家參考,對大家的學(xué)習(xí)或工作有一定的幫助,需要的朋友可以參考下2023-10-10JavaFx實現(xiàn)登錄成功跳轉(zhuǎn)到程序主頁面
這篇文章主要為大家詳細(xì)介紹了JavaFx實現(xiàn)登錄成功跳轉(zhuǎn)到程序主頁面,文中示例代碼介紹的非常詳細(xì),具有一定的參考價值,感興趣的小伙伴們可以參考一下2022-06-06詳解在SpringBoot中使用MongoDb做單元測試的代碼
這篇文章主要介紹了詳解在SpringBoot中使用MongoDb做單元測試的代碼,文中通過示例代碼介紹的非常詳細(xì),對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧2020-11-11Hibernate中使用HQLQuery查詢?nèi)繑?shù)據(jù)和部分?jǐn)?shù)據(jù)的方法實例
今天小編就為大家分享一篇關(guān)于Hibernate中使用HQLQuery查詢?nèi)繑?shù)據(jù)和部分?jǐn)?shù)據(jù)的方法實例,小編覺得內(nèi)容挺不錯的,現(xiàn)在分享給大家,具有很好的參考價值,需要的朋友一起跟隨小編來看看吧2019-03-03SpringBoot中@EnableAsync和@Async注解的使用小結(jié)
在SpringBoot中,可以通過@EnableAsync注解來啟動異步方法調(diào)用的支持,通過@Async注解來標(biāo)識異步方法,讓方法能夠在異步線程中執(zhí)行,本文就來介紹一下,感興趣的可以了解一下2023-11-11