Cake
Cake

Reputation: 503

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;
}

Upvotes: 8

Views: 9730

Answers (2)

Alex Derkach
Alex Derkach

Reputation: 759

public String toString() {
    String s =  "In klas " + this.klasCode + " zitten de volgende leerlingen:\n";
    String list = deLeerlingen.stream()
         .map(Object::toString)
         .collect(Collectors.joining());
    return s + list;
}

Upvotes: 4

flo
flo

Reputation: 10241

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();
}

Upvotes: 10

Related Questions