仅评估前两个元素的“ Hacky”解决方案:
.limit(2) .map(Optional::ofNullable) .reduce(Optional.empty(), (a, b) -> a.isPresent() ^ b.isPresent() ? b : Optional.empty());
一些基本的解释:
单个元素 [1]->映射到[Optional(1)]-> reduce
"Empty XOR Present" yields Optional(1)
=可选(1)
两个元素 [1,2]->映射到[Optional(1),Optional(2)]-> reduce可以:
"Empty XOR Present" yields Optional(1)"Optional(1) XOR Optional(2)" yields Optional.Empty
=可选。空
这是完整的测试用例:
public static <T> Optional<T> singleOrEmpty(Stream<T> stream) { return stream.limit(2) .map(Optional::ofNullable) .reduce(Optional.empty(), (a, b) -> a.isPresent() ^ b.isPresent() ? b : Optional.empty());}@Testpublic void test() { testCase(Optional.empty()); testCase(Optional.of(1), 1); testCase(Optional.empty(), 1, 1); testCase(Optional.empty(), 1, 1, 1);}private void testCase(Optional<Integer> expected, Integer... values) { Assert.assertEquals(expected, singleOrEmpty(Arrays.stream(values)));}对于贡献XOR想法和上述测试用例的Ned(OP)表示感谢!



