This code works on my system (eclipse on windows), but to make it platform independent you can use System.lineSeparator()
:
public static void main(String[] args) {
List<String> list = List.of("Hello", "to", "all");
System.out.println(fromListToString(list));
}
public static String fromListToString(List<?> list) {
String string= "";
for (int i = 0; i < list.size(); i++) {
string += System.lineSeparator() + list.get(i);
}
return string;
}
One thing I also fixed: note the List<?>
instead of the rawtype List
. This does not cause any problems here, but it might later on if you reuse this somewhere.
Ouput:
Hello
to
all
(there is a leading blank line because of the first \n
).
If you are still seeing the output in a single line, this is probably due to the way you print the result. Some loggers, for example, remove all linebreaks from messages. If you are writing the result to a file, you may need to make sure the correct line separator for your system is used, see How do I get a platform-dependent new line character?