Search code examples
javastringarraylistreverse

Java : Joining String from List<String> in reverse order


I have List<String> list = Arrays.asList("A", "B", "C");
I want to join all string inside list with delimiter , in reverse order :

//result
String joinedString = "C,B,A";

what is the best approach to achieve this?
currently I use index loop :

String joinedString = "";
List<String> list = Arrays.asList("A", "B", "C");
for (int i = list.size() - 1; i >= 0; i--) {
     String string = list.get(i);
     joinedString = joinedString + string + ",";
}
//to remove ',' from the last string
if(joinedString.length() > 0) {
    joinedString = joinedString.substring(0, joinedString.length() - 1);
}

//Output    
C,B,A

Solution

  • If you don't want to modify the list by calling Collections.reverse(List<?> list) on it, iterate the list in reverse.

    If you don't know the list type, use a ListIterator to iterate the list backwards without loss of performance, e.g. an normal i = 0; i < size() loop over a LinkedList would otherwise perform badly.

    To join the values separated by commas, use a StringJoiner (Java 8+).

    List<String> list = Arrays.asList("A", "B", "C");
    
    StringJoiner joiner = new StringJoiner(",");
    for (ListIterator<String> iter = list.listIterator(list.size()); iter.hasPrevious(); )
        joiner.add(iter.previous());
    String result = joiner.toString();
    
    System.out.println(result); // print: C,B,A