【发布时间】:2019-12-25 13:35:24
【问题描述】:
我的代码:
public static boolean searchLineOnLogFile(String...keywords)
{
Collection select = null;
try (final Stream<String> lines = Files.lines(get(getServerLog().toString())))
{
select = CollectionUtils.select(lines.collect(Collectors.toCollection(LinkedList::new)),
new Predicate()
{
public boolean evaluate(Object object)
{
String line = (String) object;
return Arrays.stream(keywords).allMatch(line::contains);
}
});
} catch (IOException e)
{
e.printStackTrace();
Assert.fail(e.getMessage());
}
select.stream().findFirst().ifPresent(firstLine -> LogAutomation.info((String)firstLine));
return select.size() > 0;
}
select.stream().findFirst().ifPresent(firstLine -> log.info((String)firstLine));
为什么我会收到“取消选中 isPresent 调用”检查?如何改进我的代码?
从我读到的所有想法都是避免空检查:
“所以不要写这样的东西:
if(optional.isPresent){
doSomething(optional.get);
}
你可以写:
optional.ifPresent(val->doSomething(val));
或者如果您愿意:
optional.ifPresent(this::doSomething);
【问题讨论】:
-
您能分享一下您收到的确切警告吗?我猜问题出在
(String)firstLine并且警告与可选方法无关 -
向我们展示
select的声明。 -
可能是因为您的
select变量已使用raw type 声明。 -
正如我所怀疑的,
select有一个 原始类型。将声明更改为Collection<String> select。其他人指出的仍然是正确的,您的异常处理......需要改进,因为在捕获异常后,您将继续使用select成为null。但这不是编译器警告的原因。 -
除了使用raw type引起的编译器警告外,很扭曲,收集一个流到一个集合,无缘无故坚持
LinkedList,然后使用第 3 方库方法CollectionUtils.select,终于再次获取流。您可以直接过滤原始流:Optional<String> o = lines.filter(line -> Arrays.stream(keywords) .allMatch(line::contains)) .findFirst(); o.ifPresent(firstLine -> LogAutomation.info((String)firstLine)); return o.isPresent();。无需收藏到LinkedList,无需第三方图书馆。
标签: java-8 intellij-inspections