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;
}
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();
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With