Lambda将List<Long>转换成List<String>出现Lambda can be replaced with method reference

15 篇文章 0 订阅

0. 说明

将Long转换为字符串的方式有很多种,如toString,valueOf,拼接字符串,new String()等。

1. 将String集合转换成Long集合

List<String> ids = Arrays.asList("1", "2", "3", "4", "5");
List<Long> collect = ids.stream().map(Long::parseLong).collect(Collectors.toList());

2. 将Long集合转换成String集合

List<Long> ids = Arrays.asList(1L, 2L, 3L, 4L, 5L);
List<String> collect = ids.stream().map(String::valueOf).collect(Collectors.toList());

3. 出现警告的原因是因为推荐使用方法引用(就是上面的写法)

// 出现警告的写法
List<Long> collect = ids.stream().map(id -> id.toString()).collect(Collectors.toList());

4. 使用String的toString()或者Long的toString()报错

// 出现报错
List<String> collect = ids.stream().map(String::toString).collect(Collectors.toList());

这是因为toString方法不需要参数,但是再map中是一个函数接口,默认是要传参数的。
可以了解一下:https://blog.csdn.net/weixin_44415764/article/details/107535276

<R> Stream<R> map(Function<? super T, ? extends R> mapper);

5. 最后,使用map方法获取对象中的数据后建议过滤一下为null的数据

List<User> list = Arrays.asList(
        new User("段誉","男",18),
        new User("段誉","男",18),
        new User("段誉","男",14),
        new User("段誉","男",27),
        new User("段誉","男",null),
        new User("段誉","男",36)
);
// 注意点:如果查询的获取list中的所有年龄时,返回结果还是6个,一般情况下建议做过滤处理
list.stream()
	.map(User::getAge)
	.filter(ObjectUtil::isNotEmpty) // 将为空的数据过滤掉
	.map(String::valueOf)
	.collect(Collectors.toList());
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值