How to join a list of strings using a delimiter in Java

2 Answers

0 votes
import java.util.Arrays;
import java.util.List;

public class MyClass {
    public static void main(String args[]) {
        List<String> lst = Arrays.asList("java", "c", "c++", "rust", "python");
        
        String delimiter = "", str = "";
        
        for (String s: lst) {
            str += delimiter + s;
            if (str != "") delimiter = ",";
        }
 
        System.out.println(str);
    }
}




/*
run:

java,c,c++,rust,python

*/

 



answered Mar 14, 2023 by avibootz
0 votes
import java.util.Arrays;
import java.util.List;

public class MyClass {
    public static void main(String args[]) {
        List<String> lst = Arrays.asList("java", "c", "c++", "rust", "python");
        
        String delimiter = ",";
        
        String str = String.join(delimiter, lst);
 
        System.out.println(str);
    }
}




/*
run:

java,c,c++,rust,python

*/

 



answered Mar 14, 2023 by avibootz

Related questions

1 answer 181 views
181 views asked Jun 26, 2019 by avibootz
1 answer 207 views
1 answer 210 views
1 answer 154 views
2 answers 164 views
...