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

Java中与JavaScript的OR操作等效的最佳实现方式是什么?

Replicate JavaScript's "First Truthy Value" Chain in Java

Great question! I’ve run into this exact need before when switching between JavaScript and Java. The good news is there are several clean, idiomatic ways to replicate that "pick the first valid value" behavior you get with JS’s || chain. Here are the best options:

Option 1: Java 9+ Optional.or() Chaining

If you’re on Java 9 or later, the Optional.or() method was built for this kind of chained fallback. Unlike orElse() (which returns the raw value), or() gives you another Optional, so you can keep chaining until you find a non-empty one:

import java.util.Optional;

String myString = Optional.ofNullable(source1)
    .or(() -> Optional.ofNullable(source2))
    .or(() -> Optional.ofNullable(source3))
    .or(() -> Optional.ofNullable(source4))
    .or(() -> Optional.ofNullable(source5))
    .orElse(null); // Replace with your preferred default value

Each or() uses a Supplier<Optional>, so it only evaluates the next source if the previous one was empty—just like JS’s short-circuit evaluation.

Option 2: Stream Filter + findFirst (Java 8+)

For broader compatibility (works in Java 8 and up), using a Stream is a concise, readable approach. Wrap all your sources in a Stream, filter out invalid values, then grab the first valid entry:

import java.util.Objects;
import java.util.stream.Stream;

String myString = Stream.of(source1, source2, source3, source4, source5)
    .filter(Objects::nonNull)
    .filter(s -> !s.isEmpty()) // Add this to skip empty strings (matching JS's "falsy" behavior)
    .findFirst()
    .orElse(null); // Or your default value

This is my go-to choice because it’s flexible—you can tweak the filters to match exactly what you consider "valid" (e.g., adding .filter(s -> !s.isBlank()) in Java 11+ to skip whitespace-only strings).

You could use nested ternary expressions, but this gets messy fast with multiple sources and is hard to maintain:

String myString = source1 != null ? source1 :
                  source2 != null ? source2 :
                  source3 != null ? source3 :
                  source4 != null ? source4 :
                  source5 != null ? source5 : null;

I only mention this for completeness—stick with the first two options unless you have a very specific edge case.

Quick Note on "Falsy" Values

Remember: JS’s || treats empty strings, 0, false, etc., as "falsy" and skips them. In Java, you’ll need to add explicit filters for these cases if you want identical behavior. For example, adding .filter(s -> !s.isBlank()) to exclude blank or whitespace-only strings.

内容的提问来源于stack exchange,提问作者supertonsky

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.20 11:32:13