Java8如何从一个list中获取某一元素集合

发布时间:2024-01-14 17:30

从一个list中获取某一元素集合

@Data
public class Person {
    private String name;
    private String age;
}
   List 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 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 stuList = new ArrayList();
		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 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 stIdList2 = stuList.stream()
				.map(Student::getId).distinct()
				.collect(Collectors.toList());
		stIdList2.forEach(s -> System.out.print(s+" "));
		/*	结果:
			123 234 345 345  
			----------
			123 234 345 
		*/
	}
}

以上为个人经验,希望能给大家一个参考,也希望大家多多支持脚本之家。

ItVuer - 免责声明 - 关于我们 - 联系我们

本网站信息来源于互联网,如有侵权请联系:561261067@qq.com

桂ICP备16001015号