20 Dec 2007

in_array() and implode() for Java

8 Comments Programming and Technology

I'm still getting to grips with Java, but there a few functions I miss coming from PHP. in_array lacks a Java equivalent, as does the implode function. Here are the equvalent methods in Java:


public static String implode(String[] ary, String delim) {
    String out = "";
    for(int i=0; i<ary.length; i++) {
        if(i!=0) { out += delim; }
        out += ary[i];
    return out;


public static boolean in_array(DefaultListModel haystack, String needle) {
    for(int i=0;i<haystack.size();i++) {
        if(haystack.get(i).toString().equals(needle)) {
            return true;
    return false;
Tags: , , , , , ,
written by
The author didn‘t add any Information to his profile yet.

8 Responses to “in_array() and implode() for Java”

  1. Reply rgfdg says:

    You should use the StringBuilder in your implode method.

  2. Reply Ramesh Thiruchelvam says:

    Java has built in functionality to search arrays using “Arrays.binarySearch”, but only drawback is that the array needs be sorted before it’s searched.

    public static boolean in_array(Object needle, Object[] haystack) {
    return (Arrays.binarySearch(haystack, needle) >= 0);

  3. Reply Echilon says:

    The problem with sorting first is that you need to loop over the array twice. You might not need it sorted.

  4. Reply Echilon says:

    Probably, I was new to Java when I posted this.

  5. Reply Programming Tips : Comparing a Variable to a Number of Values | Ganda Manurung says:

    […] in other programming language if the language doesn’t have similar function. Here is an in_array() implementation for Java. In Java, you could use any List Object such as ArrayList, Vector, HashMap or other. For C […]

  6. Reply Abhay Bhangale says:

    The apache commons String util library has a ready made function that does what PHP’s implode does. The StringUtils.join method takes as arguments a String array and a character delimiter and returns a String of values concatenated together, separated by the specified delimiter.

    import org.apache.commons.lang.StringUtils;

    //If you need to work with Collections.
    List itemList = new ArrayList();
    String selectClause = StringUtils.join(itemList.toArray() , ',' );

    //Just a raw array
    String[] itemArr = new String[]{"item1", "item2", "item3" };
    String allItemsStr = StringUtils.join(itemArr , ',');

Leave a Reply