Java8如何從一個list中獲取某一元素集合
更新時間:2022年07月07日 11:18:08 作者:芭比萌妹
這篇文章主要介紹了Java8如何從一個list中獲取某一元素集合,具有很好的參考價值,希望對大家有所幫助。如有錯誤或未考慮完全的地方,望不吝賜教
從一個list中獲取某一元素集合
@Data public class Person { private String name; private String age; } List<Person> list = new ArrayList<>(); Person person = new Person(); person.setName("1"); person.setAge(10); list.add(person); Person person1 = new Person(); person1.setName("1"); person1.setAge(10); list.add(person); //獲取person里面所有年齡集合 List<String> ageList = list.stream().map(Person::getAge).collect(Collectors.toList());
提取出list中bean的某一屬性
package com.demo; import java.util.ArrayList; import java.util.List; import java.util.stream.Collectors; public class Test6 { public static void main(String[] args) { List<Student> stuList = new ArrayList<Student>(); Student st1 = new Student("123","aaa"); Student st2 = new Student("234","bbb"); Student st3 = new Student("345","ccc"); Student st4 = new Student("345","ccc"); stuList.add(st1); stuList.add(st2); stuList.add(st3); stuList.add(st4); //1.提取出list對象中的一個屬性 List<String> stIdList1 = stuList.stream() .map(Student::getId) .collect(Collectors.toList()); stIdList1.forEach(s -> System.out.print(s+" ")); System.out.println(); System.out.println("----------"); //2.提取出list對象中的一個屬性并去重 List<String> stIdList2 = stuList.stream() .map(Student::getId).distinct() .collect(Collectors.toList()); stIdList2.forEach(s -> System.out.print(s+" ")); /* 結(jié)果: 123 234 345 345 ---------- 123 234 345 */ } }
以上為個人經(jīng)驗,希望能給大家一個參考,也希望大家多多支持腳本之家。
相關(guān)文章
Java中ShardingSphere 數(shù)據(jù)分片的實現(xiàn)
其實很多人對分庫分表多少都有點恐懼,我們今天用ShardingSphere 給大家演示數(shù)據(jù)分片,具有一定的參考價值,感興趣的小伙伴們可以參考一下2021-09-09Spring context:component-scan的使用及說明
這篇文章主要介紹了Spring context:component-scan的使用及說明,具有很好的參考價值,希望對大家有所幫助,如有錯誤或未考慮完全的地方,望不吝賜教2023-09-09java web中的servlet3 upload上傳文件實踐
這篇文章主要介紹了servlet3 upload上傳文件實踐,非常不錯,具有參考借鑒價值,需要的朋友可以參考下2017-11-11Java字符串拼接+和StringBuilder的比較與選擇
Java 提供了兩種主要的方式:使用 "+" 運算符和使用 StringBuilder 類,本文主要介紹了Java字符串拼接+和StringBuilder的比較與選擇,感興趣的可以了解一下2023-10-10ByteArrayInputStream簡介和使用_動力節(jié)點Java學(xué)院整理
ByteArrayInputStream 是字節(jié)數(shù)組輸入流。它繼承于InputStream。這篇文章主要介紹了ByteArrayInputStream簡介和使用_動力節(jié)點Java學(xué)院整理,需要的朋友可以參考下2017-05-05