SONAR:用方法引用替换此lambda [英] SONAR: Replace this lambda with a method reference

查看:3665
本文介绍了SONAR:用方法引用替换此lambda的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

Sonar告诉我用方法参考替换这个lambda

Sonar tells me "Replace this lambda with a method reference"

public class MyClass {

    private List<SomeValue> createSomeValues(List<Anything> anyList) {
        return anyList //
               .stream() //
               .map(anything -> createSomeValue(anything)) //
               .collect(Collectors.toList());
   }

    private SomeValue createSomeValue(Anything anything) {
        StatusId statusId = statusId.fromId(anything.getStatus().getStatusId());
        return new SomeValue(anything.getExternId(), statusId);
    }

}

这可能吗?我尝试了几件事,比如

Is this possible here? I tried several things, like

.map(MyClass::createSomeValue) //

但我需要将方法更改为静态。而且我不是静态方法的忠实粉丝。

but I need to change the method to static then. And I am not a big fan of static methods.

SonarQube的解释是:

Explanation of SonarQube is:


方法/构造函数引用比使用lambdas更紧凑和可读,因此是首选。

Method/constructor references are more compact and readable than using lambdas, and are therefore preferred.


推荐答案

是的,您可以使用 this :: createSomeValue

private List<SomeValue> createSomeValues(List<Anything> anyList) {
    return anyList //
            .stream() //
            .map(this::createSomeValue) //
            .collect(Collectors.toList());
}

这种方法引用被称为引用特定对象的实例方法。在这种情况下,您指的是实例的方法 createSomeValue

This kind of method reference is called "Reference to an instance method of a particular object". In this case, you are referring to the method createSomeValue of the instance this.

使用lambda表达式是否更好是一个意见问题。但是,您可以参考此答案 / brian-goetz> Brian Goetz 解释了为什么首先在语言中添加了方法引用。

Whether it is "better" or not that using a lambda expression is a matter of opinion. However, you can refer to this answer written by Brian Goetz that explains why method-references were added in the language in the first place.

这篇关于SONAR:用方法引用替换此lambda的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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