在流操作中使用方法引用和函数对象之间的区别? [英] Differences between using a method reference and function object in stream operations?

查看:109
本文介绍了在流操作中使用方法引用和函数对象之间的区别?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

使用Java 8流时,我经常发现我需要重构一个多语句lambda表达式。我将用一个简单的例子来说明这一点。假设我已经开始编写此代码:

When using Java 8 streams I often find that I need to refactor a multi-statement lambda expression. I will illustrate this with a simple example. Assume I have started writing this code:

Stream.of(1, 3).map(i -> {
    if (i == 1) {
        return "I";
    } else if (i == 3) {
        return "E";
    }
    return "";
}).forEach(System.out::println);

现在我不太喜欢地图中的大型lambda表达式致电。因此,我想从那里重构它。我看到两个选项,要么在我的班级中创建一个 Function 的实例:

Now I am not very fond of the large lambda expression in the map call. Hence, I want to refactor it out of there. I see two options, either I make an instance of Function in my class:

private static Function<Integer, String> mapper = i -> {
    if (i == 1) {
        return "I";
    } else if (i == 3) {
        return "E";
    }
    return "";
};

并像这样使用:

Stream.of(1, 3).map(mapper).forEach(System.out::println);

或者我只是做一个方法:

Or I simply make a method:

private static String map(Integer i) {
    if (i == 1) {
        return "I";
    } else if (i == 3) {
        return "E";
    }
    return "";
}

并使用方法参考:

Stream.of(1, 3).map(Test::map).forEach(System.out::println);

除了明显的品味问题外,这两种方法都有任何优点或缺点吗?

Apart from the obvious matter of taste, are there any advantages or drawbacks to either approach?

例如,我知道堆栈跟踪在方法参考案例中变得更具可读性,这是一个小优势。

For example, I know the stack traces become more readable in the method reference case, which is a small advantage.

推荐答案

除非有一些我不知道的额外魔法,否则当前的lambda实现会将你的非捕获lambda变为静态方法,并将缓存lambda实例。通过明确地执行相同的操作(静态最终对lambda的引用),您基本上复制了隐式工作,因此您最终会得到两个缓存的引用一样。你也在打败lambda实例的延迟初始化,你可以免费获得它。

Unless there's some additional magic I'm unaware of, the current lambda implementation will desugar your non-capturing lambda into a static method and will cache the lambda instance. By doing the same thing explicitly (a static final reference to a lambda), you're basically duplicating that implicit work, so you're ending up with two cached references to the same thing. You are also defeating the lazy initialization of the lambda instance, which you'd otherwise be getting for free.

这就是为什么我更喜欢方法参考:它更简单写作,更惯用,在实现方面似乎也更轻量。

This is why I would prefer just the method reference: it's simpler to write, more idiomatic, and also seems to be more lightweight in terms of implementation.

这篇关于在流操作中使用方法引用和函数对象之间的区别?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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