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)文章
關(guān)于Spring Bean實例過程中使用反射和遞歸處理的Bean屬性填充問題
本文帶領(lǐng)大家一起學(xué)習(xí)下在Spring Bean實例過程中如何使用反射和遞歸處理的Bean屬性填充,需要在類 AbstractAutowireCapableBeanFactory 的 createBean 方法中添加補全屬性方法,具體操作方法跟隨小編一起學(xué)習(xí)下吧2021-06-06
解決IDEA開發(fā)工具右側(cè)沒有Maven工具欄的問題
這篇文章主要給大家解決了IDEA開發(fā)工具右側(cè)沒有Maven工具欄的問題,文中有詳細(xì)的解決步驟,如果有遇到一樣問題的小伙伴,可以參考閱讀本文2023-09-09
Java實現(xiàn)轉(zhuǎn)換圖片格式的示例代碼
在日常的軟件開發(fā)中,處理圖像文件是一項常見任務(wù),這篇文章將實現(xiàn)實現(xiàn)一個簡單的Java程序,用于將一種圖片格式轉(zhuǎn)換為另一種格式,需要的可以了解下2025-02-02

