javaarrayslistwhitespaceapache-stringutils

Separate list items by whitespace and higher level metrics by tabs


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.


Solution

  • 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?