我有一个List
BufferedImage
的可居住的<{1}}。
List<BufferedImage> list = null; // or not null.
我发现我可以像这样刷新列表中的每个图像。
Optional.ofNullable(list)
.ifPresent(l -> l.forEach(i -> i.flush())); // ok
我能做到这一点。
Optional.ofNullable(list)
.ifPresent(l -> l.forEach(BufferedImage::flush)); // ok
为什么编译器会在我尝试这样做时抱怨?
Optional.ofNullable(list)
.ifPresent(List::forEach(BufferedImage::flush)); // not ok
答案 0 :(得分:5)
method reference(List::forEach
)无法参加论证,因此您无法撰写论证。另一方面,您可以将方法引用作为参数传递给“普通”方法调用(l.forEach(BufferedImage::flush)
)。
我认为你不能比你的倒数第二选择做得更好。
答案 1 :(得分:5)
使用空列表而不是空值更加麻烦。 Optional
让事情变得简单:
Optional.ofNullable(list)
.orElseGet(Collections::emptyList)
.forEach(BufferedImage::flush);