当前位置:   article > 正文

Stream API将对象中的某一字段取出转换为list或数组_stream 撖寡情頧柝ist

stream 撖寡情頧柝ist

在这里插入图片描述

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

所有id转换为List

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

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

在上述代码中,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);
  • 1
  • 2
  • 3

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

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

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

声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/小丑西瓜9/article/detail/323283
推荐阅读
相关标签
  

闽ICP备14008679号