简体   繁体   English

转换成 Java 8 Lambda 表达式

[英]Convert into Java 8 Lambda expression

I am very new to lambda.我对 lambda 很陌生。 Can someone please help in converting following nested loops in lambda -有人可以帮助转换 lambda 中的以下嵌套循环 -

for (Question question : questionList) {
        formattedText += NEW_LINE + localizeString(QUESTION_STRING_ID) + question.getQuestionText();
        formattedText += NEW_LINE + localizeString(ANSWER_STRING_ID);
        for (Answer answer : question.getAnswers()) {
            formattedText += answer.getAnswerText() + NEW_LINE;
        }
    }

Solution I tried我试过的解决方案

for (Question question : questionList) {
        formattedText += NEW_LINE + localizeString(QUESTION_STRING_ID) + question.getQuestionText();
        formattedText += NEW_LINE + localizeString(ANSWER_STRING_ID);
        question.getAnswers().forEach(answer -> {formattedText += answer.getAnswerText() + NEW_LINE;});
}

Not sure how can I convert both loops into single lambda expression?不知道如何将两个循环转换为单个 lambda 表达式? Also, this solution is not working since it needs formattedText to be declared as final.此外,此解决方案不起作用,因为它需要将 formattedText 声明为 final。

It may be implemented using Collectors.joining collector of Stream API:可以使用Collectors.joining收集器的 Stream API 来实现:

String prefixQ =  NEW_LINE + localizeString(QUESTION_STRING_ID);
String suffixQ =  NEW_LINE + localizeString(ANSWER_STRING_ID);
String result = questionList.stream()
    .map(q -> 
            prefixQ + q.getQuestionText() + suffixQ 
            + q.getAnswers().stream()
                    .map(Answer::getAnswerText)
                    .collect(Collectors.joining(NEW_LINE))
    )
    .collect(Collectors.joining(NEW_LINE));

You're looking for a Collector .您正在寻找Collector For example,例如,

for (Question question : questionList) {
        formattedText += NEW_LINE + localizeString(QUESTION_STRING_ID) + question.getQuestionText();
        formattedText += NEW_LINE + localizeString(ANSWER_STRING_ID);
        formattedText +=
                question.getAnswers()
                        .stream()
                        .map(Answer::getAnswerText)
                        .collect(Collectors.joining(NEW_LINE));
        formattedText += NEW_LINE;
}

That supposes that NEW_LINE represents a String .假设NEW_LINE代表一个String If instead it is a character then you could use String.valueOf(NEWLINE) as the argument to Collectors.joining() .如果相反,它是一个字符,那么您可以使用String.valueOf(NEWLINE)作为Collectors.joining()的参数。

Do note, however, that there is not actually any lambda in that at all.但是请注意,实际上根本没有任何 lambda 。 The one place where one might have been used, I use a method reference instead.在一个可能使用过的地方,我使用了方法引用。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM