1

Here is my code

String res = "";
    for (int i = 0;i < names.size();i++){
        String name = names.get(i);
        if (!res.equals(""))
                res += ",";
            res += name;
    }

I don't know how to judge wether 'res' equals "" in lambda. Thank you very much if you can help me!

5
  • 1
    A lambda expression represents an anonymous method (a method without a name) whose signature matches the single method of a functional interface that is being passed to some other method. Where exactly do you think you can place a lambda here? You could however transform the loop into a stream and use some lambda expressions when calling methods in the Stream API. Commented Mar 23, 2017 at 6:55
  • Additionally, your code seems to concatenate strings in the list with a joining separator. This can be done with names.stream().collect(Collectors.joining(",")). Without any lambda! Commented Mar 23, 2017 at 6:57
  • It works. Sorry I'm really new to java8. Commented Mar 23, 2017 at 7:03
  • Being new to Java 8 is no problem. Posting low-quality questions on SO that could have been easily answered by basic learning is, though. Commented Mar 23, 2017 at 7:07
  • Sorry, I will spend more time on basic learning. Commented Mar 23, 2017 at 7:28

1 Answer 1

4

I'm not sure a lambda expression is needed here. Did you meant to use the Stream API to refactor your code, as follows?

 String commaSeparatedNames = names.stream()
 .collect(Collectors.joining(", "));
Sign up to request clarification or add additional context in comments.

1 Comment

Starting an answer with "I'm not sure ..." and "Did you mean ..." usually disqualifies a post as an answer. To get clarification, you should post it as a comment. In fact, the question is indeed unclear.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.