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 188 views
188 views asked Jun 26, 2019 by avibootz
1 answer 220 views
1 answer 216 views
1 answer 160 views
2 answers 172 views
...