You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何通过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 an Optional containing the first element's OrderType (or empty if the list is empty), so we never risk calling get(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, so noneMatch returns true only if all elements are consistent.
  • orElse(true): Handles the empty list case. Adjust this to false if 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:

  • reduce compares each element to the first one. If a mismatch is found, it returns null and stops processing immediately (short-circuits).
  • isPresent() returns true only 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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.14 08:36:40