0

My requirement is that I have to write a java method in my class which will accept a List<String> as a parameter. Now I have to concatenate

public String encode(List<String> ls){
    StringBuffer sb = new StringBuffer();
    ListIterator<String> lis = ls.listIterator();
    while(lis.hasNext()){
        sb.append(lis.next());
        /*my code here
         * sb.append(lis.next());
         * sb.append(some delim);
         * 
         * 
         */
    }
    //my code here
    return sb.toString();       
}

Now those String in the List can contains any value(char/num/special char etc), so I cannot use common delimiters like ,/:/; etc. Please suggest me the way to do the concatenate.

Also going forward I may need to split the same concatenated string for my different method. So I need to use some delimiter or other option which can be used later for creating the list once again.

Abdullah Khan
  • 12,010
  • 6
  • 65
  • 78
Debashis
  • 11
  • 1
  • 5

2 Answers2

0

this might not be ideal but one way to do this is you concatenate by a random phrase. so while you iterate you append extra phrase or word between each string.. and later you use that phrase as delimiter..

Damian
  • 934
  • 8
  • 12
0

First, if you are just serializing an object to store/transfer, don't. Use the @Serializable annotation, and let the Java Serializing API handle that for you.

If you have to convert a convert a list to string and back yourself because reasons, I would recommend using an uncommon delimiter (a set of characters like <|>) or to be extra safe, use a uuid delimiter and start your string with it so you can identify it (like <uuid>). A specific uuid, by definition, should not appear in any list you receive. (unless you reuse a uuid and break that contract) The UUID way will be safe, even when handling lists of lists (so you won't have to escape your delimiter or do something crazy). It is cheaper though to just use <|> or , as a delimiter, and then encode/decode it to something else when converting to/from string. (if performance actually matters)

and lastly, I just have to say...

public String encode(List<String> ls){
    StringBuffer sb = new StringBuffer();
    String delim = getDelimiter();
    for(String s : ls){
        sb.append(lis.next());
        sb.append(delim);
    }
    return sb.toString();       
}

is so much simpler. Don't bother with getting an iterator unless you need to (just to keep it simple), and if you do need to use an iterator, make sure you always check "hasNext" before reading "next".

Tezra
  • 8,463
  • 3
  • 31
  • 68