JAVA8 stream使用方法汇总

本文详细介绍Java Stream API的各种应用场景,包括字段转换、过滤、汇总计算、排序、去重及实体拷贝等操作,帮助开发者掌握Stream API的核心功能。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

	平时stream和parallelstream使用非常多,现以stream为例子总结一下: 
		List<Test> list = new ArrayList()

一、list 取单一字段 转targetList
List targetList = list.stream().map(WeekDuty::getId).collect(Collectors.toList())

二、list 取指定字段 转targetMap
Map<Long,Test> targetMap = list.stream().collect(Collectors.toMap(Test::getId,test -> test));
Map<Long,String> targetMap = list.stream().collect(Collectors.toMap(Test::getId,test -> test.getName));

三、list 分组 转 targetMap

//按对象分组
Map<Long, List<Test>> targetMap= list.stream().collect(Collectors.groupingBy(Test::getId));

//逗号组合姓名字符串
Map<Long,String> targetMap= list.stream().collect(Collectors.groupingBy(Test::getId, Collectors.mapping(Test::getName, Collectors.joining(","))));

四、list 过滤 转 targetList

//过滤id大于10的
    	List<Test> targetList = list.stream().filter(a -> a.getId() > 10).collect(Collectors.toList());

五、汇总 计算
//list 求和 转 sumAge
int sumAge = list.stream().mapToInt(Test::getAge).sum();
//list 求最小日期 minEntryDate
Date minEntryDate = list.stream().map(Test::getEntryDate).min(Date::compareTo).get();
//list 求最大日期 maxEntryDate
Date maxEntryDate = userList.stream().map(Test::getEntryDate).max(Date::compareTo).get();
六、排序
//单字段排序,根据id排序 targetList
targetList = list.sort(Comparator.comparingTest::getId));
//多字段排序,根据id,年龄排序
targetList = list.sort(Comparator.comparing(User::getId).thenComparing(User::getAge));
七、去重
List distinctIdList = list.stream().distinct().collect(Collectors.toList());

List<Test> distinctIdList = list.stream().filter(distinctByKey(b -> b.getId())).collect(Collectors.toList());
            
自己定义 distinctByKey函数
	public static <T> Predicate<T> distinctByKey(Function<? super T, Object> keyExtractor) {
    		Map<Object, Boolean> seen = new ConcurrentHashMap<>();
    		return t -> seen.putIfAbsent(keyExtractor.apply(t), Boolean.TRUE) == null;
 }

八、不同实体的list拷贝

List test1List = list.stream().map(p->{Test1 e = new Test1();
e.setIp(p.geId());
e.setEndDate(p.getEnd());
return e;}).collect(Collectors.toList());
总结:
parallelstream和stream使用方式基本相同,但使用场景不一样;
parallelstream需要注意线程安全的问题。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值