Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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
like image 801
m fauzan abdi Avatar asked Oct 18 '25 10:10

m fauzan abdi


2 Answers

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
like image 179
Andreas Avatar answered Oct 19 '25 23:10

Andreas


The simplest is to use Collections#reverse and String#join.

List<String> list = Arrays.asList("A", "B", "C");
Collections.reverse(list);
String joinedString = String.join(",", list);
like image 37
RaminS Avatar answered Oct 20 '25 00:10

RaminS



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!