我的 ViewValue 类定义如下:
class ViewValue {
private Long id;
private Integer value;
private String description;
private View view;
private Double defaultFeeRate;
// getters and setters for all properties
}
在我的代码中的某个位置,我需要将 ViewValue 实例列表转换为包含相应 ViewValue 中 id 字段值的列表。
我使用 foreach 循环来做到这一点:
List<Long> toIdsList(List<ViewValue> viewValues) {
List<Long> ids = new ArrayList<Long>();
for (ViewValue viewValue : viewValues) {
ids.add(viewValue.getId());
}
return ids;
}
有没有更好的方法来解决这个问题?
最佳答案
我们可以使用 java 8 通过一行代码来完成它
List<Long> ids = viewValues.stream().map(ViewValue::getId).collect(Collectors.toList());
了解更多信息: Java 8 - Streams
关于Java - 将对象列表映射到具有其属性属性值的列表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48585678/