Stream#reduce()的System.out.println()意外地打印出“Optional []”。结果 [英] System.out.println() of Stream#reduce() unexpectedly prints "Optional[]" around result

查看:198
本文介绍了Stream#reduce()的System.out.println()意外地打印出“Optional []”。结果的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我开始学习Java 8的Lambda表达式,并写下以下程序来获取列表中所有数字的总和:

I started to learn Lambda expressions of Java 8, and wrote below program to get sum of all numbers in the list:

import java.util.Arrays;
import java.util.List;

public class MainClass {

    public static void main(String[] args) {
        List<Integer> number = Arrays.asList(1, 2, 3, 4, 5);

        System.out.println(number.stream().reduce((c,e) -> {
            return c + e;
        }));
    }
}

我原以为输出为:


15

15

但我得到了:


可选[15]

Optional[15]

Java版本: 1.8.0_45


  • 请解释 Optional [] 在输出中的含义是什么?

  • 它在Java 8中有什么意义吗?

  • Please explain what does Optional[] means in the output?
  • Does it has any significance in Java 8?

推荐答案

来自 Java Docs for Stream#reduce(),我们看到reduce操作返回 Optional< T> 。如果有的话,可选只会包含一个值值存在,否则为空。

From the Java Docs for Stream#reduce(), we see that the reduce operation returns an Optional<T>. An Optional simply wraps a value if there is a value present, otherwise is "empty".

上的重要操作> 包括可选#isPresent ,可以让您知道是否有什么在可选或不可选中,可选#get ,返回包含在Optional中的 T ,如果在Empty上调用则抛出异常,并且可选#orElse ,返回 T 包含在Optional if present中,或者返回默认值,如果在Empty上调用则提供。

Important operations on Optional include Optional#isPresent, which lets you know if there is something in the Optional or not, Optional#get, which returns the T wrapped in the Optional and throws an exception if called on Empty, and Optional#orElse which returns the T wrapped in the Optional if present, or the returns the default value provided if called on Empty.

对于你的情况,背后的基本原理减少() returnin g 可选<整数> 是您尝试减少的列表可能为空。在这种情况下,应该返回的 Integer 定义不明确。为了您的具体意图 0 是可以接受的(因为空列表中元素的总和是 0 ),因此你可以得到如下总和:

For your case, the rationale behind reduce() returning an Optional<Integer> is that the list you're trying to reduce may be empty. In that case, the Integer that should be returned is not well defined. For your specific intention 0 would be acceptable (As the sum of the elements in an empty list is 0), thus you can get the sum as follows:

int sum = number.stream().reduce((c,e) -> c + e).orElse(0);

这样,即使列表为空,您仍然会得到一个定义总和的结果清单。

That way, even if the list is empty, you will still get a result that defines the sum of the list.

这篇关于Stream#reduce()的System.out.println()意外地打印出“Optional []”。结果的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆