【问题标题】:convert method to java 8 lambda将方法转换为 java 8 lambda
【发布时间】:2016-09-23 02:45:03
【问题描述】:

如何在函数式编程中以更直观的方式使用 Java 8 lambda / stream() 编写此方法?

int animation = R.style.DialogAnimationSlideHorizontal;
String body;
String subject = mSubjectView.getText().toString();
BaseDialog dialog = dialogFactory.getType(DialogTypes.DIALOG_FULL);

if (!checkFields()) {
    // one of the recipients is invalid.
    body = getString(R.string.bad_address);
    dialog.showDialog(body, animation, new DialogBuilder.Positive() {
        @Override
        public void handleClick(DialogInterface dialogInterface, View view) {
            // do nothing
        }
    });
} else if (Helpers.isEmpty(subject)) {
        // Yup, empty... send the message without a subject?
        body = getString(R.string.empty_subject_compose);
        dialog.showDialog(body, animation, new DialogBuilder.Positive() {
            @Override
            public void handleClick(DialogInterface dialogInterface, View view) {
                // user accepted to send anyway.
                mWebView.getComposeContent();
            }
        });
} else {
    // everything is correct! send the message.
    mWebView.getComposeContent();
}

【问题讨论】:

  • 尝试进行更广泛的检修,包括checkFields() 等方法(如果该代码检查一组字段,则它是流的良好候选者)。功能性与整体功能性风格架构搭配使用效果最佳。

标签: java lambda functional-programming java-8 java-stream


【解决方案1】:

将所有匿名类替换为像

这样的 lambdas
new DialogBuilder.Positive() {
    @Override
    public void handleClick(DialogInterface dialogInterface, View view) {
       ...
    }
}

               |
               V

(dialogInterface, view) -> { /*do nothing*/ }
(dialogInterface, view) -> { mWebView.getComposeContent(); }

而且我看不到如何在这里应用 Stream API。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-06-14
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-10-06
    相关资源
    最近更新 更多