Suppose I have a list of Book where the number of books can be quite large. I'm logging the isbn of those books. I've come up with two approaches, would there be any performance difference / which approach is considered as better ?
My concern with 2) will be whether the length of String is too long to become an issue. Refer to How many characters can a Java String have?, it's not likely it will hit the max number of characters, but I'm not sure on the point about "Half your maximum heap size", and whether it's actually a good practice to construct a long String.
- Convert to list of String
List<Book> books = new ArrayList<>();
books.add(new Book().name("book1").isbn("001"));
books.add(new Book().name("book2").isbn("002"));
if (books != null && books.size() > 0) {
List<String> isbns = books.stream()
.map(Book:getIsbn)
.collect(Collectors.toList());
logger.info("List of isbn = {}", isbns);
} else {
logger.info("Empty list of isbn");
}
- Using StringBuilder and concatenate as one long String
List<Book> books = new ArrayList<>();
books.add(new Book().name("book1").isbn("001"));
books.add(new Book().name("book2").isbn("002"));
if (books != null && books.size() > 0) {
StringBuilder strB = new StringBuilder();
strB.append("List of isbn: ");
books.stream()
.forEach(book -> {
strB.append(book.getIsbn());
strB.append("; ");
});
logger.info("List of isbn = {}", strB.toString());
} else {
logger.info("Empty list of isbn");
}