google guava nesting joiner
The Joiner in Google Guava (a superset of Google collection) is really cool. My question is that is there a simple way to deal with nesting collections? For example, I have a matrix, which is a list of rows, and each row is a list of numbers:
List<ArrayList<Integer>> matrix = Lists.newArrayList( //
Lists.newArrayList(1, 2, 3), //
Lists.newArrayList(4, 5, 6), //
Lists.newArrayList(7, 8, 9));
开发者_JAVA百科
I want to output this matrix by using new line as the row separator and "," as the separator for the number. That is:
1, 2, 3
4, 5, 6
7, 8, 9
If it is just one row, I can simply use some code like "Joiner.on(",").nums". For this nested case, I have to loop all the rows.
Is there a more elegant way?
Thanks!
Looping seems fine to me. That said, you could do:
// implementation is simple enough
public static Function<Iterable<?>, String> joinFunction(Joiner joiner) { ... }
String string = Joiner.on('\n').join(
Iterables.transform(matrix, joinFunction(Joiner.on(", "))));
You are losing some efficiency there because you can't have all the text appended to a single StringBuilder
, though, and I think a loop would probably be easier to understand.
In Java 8, one could use lambda:
String s = matrix.stream()
.map(row -> row.stream().map(Object::toString).collect(Collectors.joining(",")))
.collect(Collectors.joining("\n"));
精彩评论