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

Stream API将对象中的某一字段取出转换为list或数组_第1张图片

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[]数组。要实现这一点,您可以通过使用toArray()方法将List转换为Long[]数组。以下是修改后的代码示例:

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

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

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

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

你可能感兴趣的:(庖丁解牛,java,stream)