我正在尝试将以下代码放入流中:
for (Engine engine : engines) {
if (engine.getId().equals(rollingStockId)) {
return engine;
}
}
for (TrainSet trainSet : trainSets) {
if (trainSet.getId().equals(rollingStockId)) {
return trainSet;
}
}
throw new LogicException("there is no train-set or engine with ID "+ rollingStockId);
我已经尝试过return engines.stream().filter(engine -> engine.getId().equals(rollingStockId);
和其他一些变体,但它们都不起作用。我对 Stream API 比较陌生。这是否可能或有用?
最佳答案
你走在正确的道路上。第一次调用stream()
然后filter
然后然后 findFirst()
然后 Optional<T>.get()
。就像,
return engines.stream()
.filter(engine -> engine.getId().equals(rollingStockId))
.findFirst()
.get(); // <-- but better to return the Optional type.
关于java - 如果在 for-each-loop 内进行 Stream,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60404032/