这篇文章主要介绍了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+" "));
		/*	结果:
			123 234 345 345  
			----------
			123 234 345 
		*/
	}
}
以上为个人经验,希望能给大家一个参考,也希望大家多多支持编程学习网。
				 沃梦达教程
				
			本文标题为:Java8如何从一个list中获取某一元素集合
				
        
 
            
        基础教程推荐
             猜你喜欢
        
	     - 运用El表达式截取字符串/获取list的长度实例 2023-08-01
 - JavaWeb 实现验证码功能(demo) 2024-04-14
 - 是否适合从javabean类更新数据库? 2023-11-04
 - 深入理解约瑟夫环的数学优化方法 2024-03-07
 - Java中EnvironmentAware 接口的作用 2023-01-23
 - Java+mysql实现学籍管理系统 2023-03-16
 - 使用Java和WebSocket实现网页聊天室实例代码 2024-02-25
 - Java编写实现窗体程序显示日历 2023-01-02
 - JSP 动态树的实现 2023-12-17
 - springboot下使用shiro自定义filter的个人经验分享 2024-02-27
 
    	
    	
    	
    	
    	
    	
    	
    	
						
						
						
						
						
				
				
				
				