To group a list of strings using a prefix and suffix you can use Collectors.joining(CharSequence delimiter, CharSequence prefix,CharSequence suffix))
, example :
import java.util.List;
import java.util.stream.Collectors;
public class Test {
public static void main(String[] args) {
List colors = List.of("Red", "Blue", "Yellow");
String result = colors.stream().collect(Collectors.joining(" , ", "{", "}"));
System.out.println(result);
}
}
this will print {Red , Blue , Yellow}
and if list is empty it will print {}
Note that:
- I think you should review your model design ^^ !
- I've used
List.of()
in my example to demonstrate the "how to", knowing that it requires java 9 or above