本篇內容主要講解“JDK8怎么通過Stream對List、Map操作和互轉”,感興趣的朋友不妨來看看。本文介紹的方法操作簡單快捷,實用性強。下面就讓小編來帶大家學習“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());
以上三種方式不同之處在于排序的處理。參考鏈接:
/tupian/20230522/page-not-found 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));
到此,相信大家對“JDK8怎么通過Stream對List、Map操作和互轉”有了更深的了解,不妨來實際操作一番吧!這里是創新互聯建站,更多相關內容可以進入相關頻道進行查詢,關注我們,繼續學習!
當前名稱:JDK8怎么通過Stream對List、Map操作和互轉-創新互聯
標題來源:http://vcdvsql.cn/article36/ceohsg.html
成都網站建設公司_創新互聯,為您提供自適應網站、域名注冊、服務器托管、靜態網站、關鍵詞優化、網站改版
聲明:本網站發布的內容(圖片、視頻和文字)以用戶投稿、用戶轉載內容為主,如果涉及侵權請盡快告知,我們將會在第一時間刪除。文章觀點不代表本網站立場,如需處理請聯系客服。電話:028-86922220;郵箱:631063699@qq.com。內容未經允許不得轉載,或轉載時需注明來源: 創新互聯