Stream API将对象中的某一字段取出转换为list或数组

在这里插入图片描述

List<DevicePartMaintain> devicePartMaintainList = 
devicePartMaintainMapper.selectDevicePartMaintainByMitId(mitId);

所有id转换为List

要使用Stream流获取devicePartMaintainList中所有的id,您可以使用stream()方法将列表转换为流,然后使用map()方法从每个DevicePartMaintain对象中提取id,最后使用collect()方法将结果收集到一个列表中。以下是示例代码:

List<Long> idList = devicePartMaintainList.stream()
    .map(DevicePartMaintain::getId)
    .collect(Collectors.toList());

在上述代码中,stream()方法将devicePartMaintainList转换为一个流。然后,map()方法将每个DevicePartMaintain对象映射为其对应的id。最后,collect(Collectors.toList())方法将所有的id收集到一个列表中。

请注意,上述示例假设每个DevicePartMaintain对象都有一个名为id的getter方法,用于返回其对应的id。您需要根据实际情况进行调整。

通过这种方式,您可以使用Stream流非常方便地获取devicePartMaintainList中的所有id。

所有id转换为数组

在上述代码中,您将Stream流收集到一个List<Long>中,但是您想要将其转换为Long[]数组。要实现这一点,您可以通过使用toArray()方法将List<Long>转换为Long[]数组。以下是修改后的代码示例:

Long[] idArray = devicePartMaintainList.stream()
    .map(DevicePartMaintain::getId)
    .toArray(Long[]::new);

在上述代码中,toArray(Long[]::new)List<Long>转换为Long[]数组。

请注意,如果DevicePartMaintain的id属性是基本类型(例如long)而不是对象类型(例如Long),则需要将toArray()方法的参数Long[]::new替换为toArray(size -> new long[size])

通过这种方式,您可以将devicePartMaintainList中的所有id转换为Long[]数组。

  • 1
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

IT小辉同学

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值