Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java - Add to a string within a Lambda expression

I'm quite new to Java, I tried looking around on StackOverflow/Google but couldn't find an answer to my problem.

Problem: I have a String with the name of 's' that I have set to a sentence. Then, I want to use the Lambda .forEach loop to iterate over a list of objects, retrieving the toString() from the objects and adding it to this 's' String.

This is my code:

public String toString() {
    String s =  "In klas " + this.klasCode + " zitten de volgende leerlingen:\n";
    deLeerlingen.forEach(leerlingen -> {
        s += leerlingen.toString();
    });
    return s;
}
like image 662
Cake Avatar asked Jan 06 '23 12:01

Cake


1 Answers

Directly using a String variable this way is not possible as lambda-external variables have to be (effectively) final.

You can use a StringBuilder instead:

public String toString() {
    StringBuilder b = new StringBuilder();

    b.append("In klas ");
    b.append(this.klasCode);
    b.append(" zitten de volgende leerlingen:\n");

    deLeerlingen.forEach(leerlingen -> {
        b.append(leerlingen.toString());
    });

    return b.toString();
}
like image 150
flo Avatar answered Jan 09 '23 18:01

flo