I concatenated a list of results from a DB query after a loop and got the expected output, but without any separator between the values:
dbDemo = ""
List<EntityClass> queryResultlist = query.getResultList();
for (EntityClass resultRow : queryResultlist) {
dbDemo = dbDemo.concat(resultRow.getId());
}
System.out.println(dbDemo);
Output:Test1Test2Test3
Is there a way to add a line break separator to the values to have a pretty print? Something like this:
Test1
Test2
Test3
or
Test1, Test2, Test3
or
"Test1", "Test2," "Test3"
CodePudding user response:
append newline at the end
dbDemo = ""
List<EntityClass> queryResultlist = query.getResultList();
for (EntityClass resultRow : queryResultlist) {
dbDemo = dbDemo.concat(resultRow.getId() "\n");
}
System.out.println(dbDemo);
Output:
Test1
Test2
Test3
CodePudding user response:
You may want to use StringJoiner
, which makes it easier to join strings with separators, prefixes and suffixes. You can use it as such:
StringJoiner stringJoiner = new StringJoiner(", "); // Use System.lineSeparator() for newlines
List<EntityClass> queryResultlist = query.getResultList();
for (EntityClass resultRow : queryResultlist) {
stringJoiner.add(resultRow);
}
String dbDemo = stringJoiner.toString();
System.out.println(dbDemo);
Output:
Test1, Test2, Test3
CodePudding user response:
Another solution, using Stream
s:
final List<EntityClass> queryResultList = List.of(
EntityClass.of(13),
EntityClass.of(1337),
EntityClass.of(42));
final String delimiter = ", ";
System.out.println(queryResultList.stream()
.map(EntityClass::getId)
.map(Object::toString)
.collect(Collectors.joining(delimiter)));
Output:
13, 1337, 42
We map each EntityClass
to its id
(which gets autoboxed from int
to Integer
), and from there transform it to a String
by calling Object::toString
. Finally, we concatenate each entry in the stream by appending ", "
.
If we want to delimit each entry by a line break instead of ", "
, we can just set delimiter =
System.lineSeparator;
, resulting in the following output:
13
1337
42