Search code examples
javaarraysstringsortingstringbuffer

StringBuffer Array to String Array - Java


I need to convert a StringBuffer Array to String Array for sorting. Is there any method in Java?

Below is my code and i am trying to sort the values(input1) in alphabetical order that contains the first letter as UpperCase and ignoring other values.

import java.util.*;
public class IPLMatch
{
    public static void main(String args[])
    {

        int input1 = 4;
        String input2[] = {"One","two","Three","foUr"}, output[];
        StringBuffer[] temp = new StringBuffer[input1];
        int j = 0, k = 0;
        for(int i = 0; i < input1; i++)
        {
            boolean isUpperCase = Character.isUpperCase(input2[i].charAt(0));
            if(isUpperCase)
            {
                temp[j++] = new StringBuffer(input2[i]);
            }
        }
                //I need convert my stringbuffer array (temp) to String array for sorting
        Arrays.sort(temp); 
        System.out.print("{");
        for(int i = 0; i < temp.length; i++)
        {
            System.out.print( temp[i]+ ",");
        }
        System.out.print("\b}");
    }
}

Solution

  • I don't think there's a built-in method. However, it's easy to write one:

    public static String[] toStringArr(StringBuffer sb[]) {
        if (sb == null) return null;
        String str[] = new String[sb.length];
        for (int i = 0; i < sb.length; i++) {
            if (sb[i] != null) {
                str[i] = sb[i].toString();
            }
        }
        return str;
    }
    

    or, if you feel like writing a generic method:

    public static<T> String[] toStringArr(T arr[]) {
        if (arr == null) return null;
        String ret[] = new String[arr.length];
        for (int i = 0; i < arr.length; i++) {
            if (arr[i] != null) {
                ret[i] = arr[i].toString();
            }
        }
        return ret;
    }
    

    This takes any array of objects, applies toString() to every element, and returns the resulting array of strings.