JDK8通過Stream 對List,Map操作和互轉的實現
更新時間:2019年09月19日 11:36:09 作者:hgc0907
這篇文章主要介紹了JDK8通過Stream 對List,Map操作和互轉的實現,文中通過示例代碼介紹的非常詳細,對大家的學習或者工作具有一定的參考學習價值,需要的朋友們下面隨著小編來一起學習學習吧
1、Map數據轉換為自定義對象的List,例如把map的key,value分別對應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對象轉換為其他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轉換為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));
以上就是本文的全部內容,希望對大家的學習有所幫助,也希望大家多多支持腳本之家。
相關文章
SpringBoot中yml多環(huán)境配置的3種方法
這篇文章主要給大家介紹了SpringBoot中yml多環(huán)境配置的3種方法,文中有詳細的代碼示例供大家參考,對大家的學習或工作有一定的幫助,需要的朋友可以參考下2023-10-10詳解在SpringBoot中使用MongoDb做單元測試的代碼
這篇文章主要介紹了詳解在SpringBoot中使用MongoDb做單元測試的代碼,文中通過示例代碼介紹的非常詳細,對大家的學習或者工作具有一定的參考學習價值,需要的朋友們下面隨著小編來一起學習學習吧2020-11-11Hibernate中使用HQLQuery查詢全部數據和部分數據的方法實例
今天小編就為大家分享一篇關于Hibernate中使用HQLQuery查詢全部數據和部分數據的方法實例,小編覺得內容挺不錯的,現在分享給大家,具有很好的參考價值,需要的朋友一起跟隨小編來看看吧2019-03-03SpringBoot中@EnableAsync和@Async注解的使用小結
在SpringBoot中,可以通過@EnableAsync注解來啟動異步方法調用的支持,通過@Async注解來標識異步方法,讓方法能夠在異步線程中執(zhí)行,本文就來介紹一下,感興趣的可以了解一下2023-11-11