How to write an equivalent to PHP implode(string $separator, array $array): string in Java

1 Answer

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

public class ImplodeExample {

    // Custom implode method (similar to your C++ version)
    public static String implode(String separator, List<String> elements) {
        StringBuilder result = new StringBuilder();
        for (int i = 0; i < elements.size(); i++) {
            if (i > 0) {
                result.append(separator);
            }
            result.append(elements.get(i));
        }
        
        return result.toString();
    }

    public static void main(String[] args) {
        List<String> words = Arrays.asList("May", "the", "Force", "be", "with", "you");

        // Using custom implode
        System.out.println(implode("-", words));

        // Idiomatic Java: using String.join
        System.out.println(String.join("-", words));
    }
}



/*
run:

May-the-Force-be-with-you
May-the-Force-be-with-you

*/

 



answered Dec 5, 2025 by avibootz

Related questions

...