如何通过Lambda表达式移除get(0),判断List中OrderType是否一致?
Yes, you can absolutely eliminate the get(0) call while keeping the short-circuit behavior of your original loop (and using noneMatch as you requested). Here's how to do it cleanly with Java Streams, while handling edge cases like empty lists:
Core Solution Using noneMatch
This approach aligns directly with your request to use noneMatch and avoids risky index access:
// Safely retrieve the first OrderType (no IndexOutOfBoundsException for empty lists) Optional<OrderType> firstOrderType = openStrategies.stream() .map(strategy -> strategy.calculate().getOrderType()) .findFirst(); // Check if all elements match the first type (treat empty list as valid by default) boolean success = firstOrderType .map(type -> openStrategies.stream() .noneMatch(strategy -> !strategy.calculate().getOrderType().equals(type)) ) .orElse(true);
Explanation:
findFirst(): Returns anOptionalcontaining the first element'sOrderType(or empty if the list is empty), so we never risk callingget(0)on an empty list.noneMatch(): Behaves exactly like your original loop—it stops processing immediately when it finds a mismatch. The predicate checks for elements that don't match the sample, sononeMatchreturnstrueonly if all elements are consistent.orElse(true): Handles the empty list case. Adjust this tofalseif an empty list should be considered a failure instead.
Avoiding Recalculation of calculate()
The above solution calls calculate() on the first element twice. If calculate() is expensive or has side effects, use this iterator + stream hybrid to process elements sequentially without recalculation:
boolean success = true; Iterator<Mt4Strategy> iterator = openStrategies.iterator(); if (iterator.hasNext()) { OrderType sample = iterator.next().calculate().getOrderType(); success = StreamSupport.stream( Spliterators.spliteratorUnknownSize(iterator, Spliterator.ORDERED), false // Sequential stream preserves short-circuit behavior ) .map(Mt4Strategy::calculate) .noneMatch(action -> !action.getOrderType().equals(sample)); } // Empty list case: success remains true (modify if needed)
Pure Stream Short-Circuiting Alternative
If you prefer a fully stream-based solution without iterators, use reduce to track consistency without recalculating any elements:
boolean success = openStrategies.stream() .map(Mt4Strategy::calculate) .map(Mt4Action::getOrderType) .reduce((first, next) -> first.equals(next) ? first : null) .isPresent() || openStrategies.isEmpty();
How This Works:
reducecompares each element to the first one. If a mismatch is found, it returnsnulland stops processing immediately (short-circuits).isPresent()returnstrueonly if all elements matched. We add|| openStrategies.isEmpty()to explicitly handle the empty list case.
All these solutions eliminate the get(0) call while maintaining the efficiency of your original loop.
内容的提问来源于stack exchange,提问作者Pavel

