Reputation: 113
I have the following functions:
public String tabSerializer(String log, String time) {
StringJoiner joiner = new StringJoiner("\t");
addValue(company, joiner);
addValue(users, joiner);
...
return joiner.toString();
}
private static void addValue(Object value, StringJoiner joiner){
if(value instanceof List){
addValuesFromList((List<?>)value, joiner);
}
else{
joiner.add(String.valueOf(value));
}
}
private static void addValuesFromList(List<?> arr, StringJoiner joiner) {
for(int i=0; i<arr.size(); i++){
Object value = arr.get(i);
addValue(value, joiner);
}
}
company is a List of strings. Example: [Apple, mango]. I am trying to separate all the values passed in tabSerializer() function by a tab. However, using my current code, I am getting tabs even between list values (eg, apple mango) instead of whitespace.
I want to separate list values by whitespaces while still separate all higher level dimesnions by tabs.
I tried adding: value= value + " " in the "addValuesFromList()"
function but don't know how to further use that to integrate with the joiner.
Any help would be appreciated.
Upvotes: 0
Views: 61
Reputation: 4120
Or if you still want to use StringJoiner use second joiner in addValuesFromList.
private static void addValuesFromList(List<?> arr, StringJoiner joiner) {
StringJoiner spaceJoiner = new StringJoiner(" ");
for (int i = 0; i < arr.size(); i++) {
Object value = arr.get(i);
spaceJoiner.add(String.valueOf(value));
}
String spacedValue = spaceJoiner.toString();
addValue(spacedValue, joiner);
}
will it do what you need?
Upvotes: 2
Reputation: 159096
StringJoiner
is a nice helper class to:
... construct a sequence of characters separated by a delimiter ...
Since you need multiple delimiters, StringJoiner
is not the best tool for the job.
Instead, just do it yourself using StringBuilder
:
public String tabSerializer(Object... values) {
StringBuilder buf = new StringBuilder();
boolean first = true;
for (Object value : values) {
if (first)
first = false;
else
buf.append('\t');
appendValue(buf, value);
}
return buf.toString();
}
private static void appendValue(StringBuilder buf, Object value) {
if (value instanceof List) {
appendListValues(buf, (List<?>) value);
} else {
buf.append(value);
}
}
private static void appendListValues(StringBuilder buf, List<?> list) {
boolean first = true;
for (Object value : list) {
if (first)
first = false;
else
buf.append(' ');
buf.append(value);
}
}
Test
System.out.println(tabSerializer("Foo", Arrays.asList("A", "B"), "Bar"));
Output (tab visualized using → arrow)
Foo→A B→Bar
Upvotes: 0