0

I'm trying to use a lambda expression in a forEach loop to concatenate to a variable "i" a string that is evaluated for each object.

here is the code

private String getStringActiveRooms(@NotNull ArrayList<Chat_room> c){
    String i;
    c.forEach( (chat_room) -> i = i.concat(chat_room.getName() + "[" + chat_room.activeUsers() + "/" + chat_room.maxUsers() + "]" + ", "));

    return i;

}

It throws me an error because external variables must be final to be used in a lambda expression.
But if I make final the variable I can't change it and the code didn't work.

Does anyone have a solution?

ThaDome23
  • 90
  • 1
  • 11

1 Answers1

2

You can use StringBuffer

private String getStringActiveRooms(@NotNull ArrayList<Chat_room> c){
    final StringBuffer i = new StringBuffer();
    c.forEach( (chat_room) -> i.append(chat_room.getName() + "[" + chat_room.activeUsers() + "/" + chat_room.maxUsers() + "]" + ", "));

    return i.toString();

}

In addition you have to know that using StringBuffer is better from a performance point of view: String are immutable this means that if you have a String i every iteration i + "something" creates a new String object in the heap space allocating memory for a temporary variable

Renato
  • 2,077
  • 1
  • 11
  • 22