Java: sort a String array, whose strings represent int

java sort string array
sort list of list of strings java
sort number string java
sort string java
java sort array
java sort arraylist of integers
how to sort string as number
java sort string array numerically

I have String[] array like


I want to sort it in numerical order, not in alphabetical order.

If I use


I obtain


instead of


I think by far the easiest and most efficient way it to convert the Strings to ints:

int[] myIntArray = new int[myarray.length];

for (int i = 0; i < myarray.length; i++) {
    myIntArray[i] = Integer.parseInt(myarray[i]);

And then sort the integer array. If you really need to, you can always convert back afterwards:

for (int i = 0; i < myIntArray.length; i++) {
    myarray[i] = "" + myIntArray[i];

An alternative method would be to use the Comparator interface to dictate exactly how elements are compared, but that would probably amount to converting each String value to an int anyway - making the above approach much more efficient.

sorting - Java: sort a String array, whose strings represent int, I think by far the easiest and most efficient way it to convert the String s to int s: int​[] myIntArray = new int[myarray.length]; for (int i = 0;  To sort a String array in Java, you need to compare each element of the array to all the remaining elements, if the result is greater than 0, swap them. One solution to do so you need to use two loops (nested) where the inner loop starts with i+1 (where i is the variable of outer loop) to avoid repetitions in comparison.

Try a custom Comparator, like this:

    Arrays.sort(myarray, new Comparator<String>() {
        public int compare(String o1, String o2) {
            return Integer.valueOf(o1).compareTo(Integer.valueOf(o2));

Hope you like it!

Print array of strings in sorted order without copying one string into , Print array of strings in sorted order without copying one string into another · Maximum number of unique Value to be subtracted from array elements to make sum of all elements equals K · Check if the given string void printInSortedOrder(string arr[], int n) Java. filter_none. edit close. play_arrow. link brightness_4 code  public static void sort(int[] arr, int from_Index, int to_Index) arr - the array to be sorted from_Index - the index of the first element, inclusive, to be sorted to_Index - the index of the last element, exclusive, to be sorted This method doesn't return any value. A Java program to sort an array of integers in ascending order.

I found this article about sorting strings by numeric sorting also for strings that may or may not contain numbers:

The Alphanum Algorithm

There is a Java implementation example linked from the article. With that class you should be able to sort your arrays numerically like this:

Arrays.sort(myarray, new AlphanumComparator());

Sort an array of strings according to string lengths, Strings according to their lengths. import java.util.*;. class solution. {. // Function to print the sorted array of string. // void printArraystring(string,int);. // Function to  Description The java.util.Arrays.toString(int[]) method returns a string representation of the contents of the specified int array. The string representation consists of a list of the array's elements, enclosed in square brackets ("[]"). Adjacent elements are separated by the characters ", " (a comma followed by a space).

Your desired output contains the numerical order of corresponding integers of your strings. So simply you cannot avoid conversion of strings to integers. As an alternative comparator to vikingsteve's you can use this:

Arrays.sort(array, new Comparator<String>() {
    public int compare(String str1, String str2) {
        return Integer.parseInt(str1) - Integer.parseInt(str2);

How to sort ArrayList in Java, Java program to sort any arraylist of strings alphabetically and descending order. Sort list of strings. //Unsorted list. List<String>  A Java String Array is an object that holds a fixed number of String values. Arrays in general is a very useful and important data structure that can help solve many types of problems. It's simplicity on how to access contents through index makes it powerful yet user-friendly.

U can use sol-1 if it contains only numbers in string format.

Solution-1: -
String []arr = {"3","2","4","10","11","6","5","8","9","7"};
        Set<Integer> set = new TreeSet<Integer>();
        for(String s:arr){
            System.out.print(s+"  ");
        Integer i = new Integer("4f");
String []arr = {"3","2","4","10","11","6","5","8","9","7","jgj","ek"};
        Set<Integer> intSet = new TreeSet<Integer>();
        Set<String> strSet = new TreeSet<String>();
        for(String s:arr){
            try {
                int i = Integer.parseInt(s);
            } catch (NumberFormatException e) {
        List<String> result = new ArrayList<String>();
        for(int val:intSet){

Write one CustomComparator class and pass it to the sort() method.

public class CustomComparator implements Comparator<String>{

    public int compare(String s1, String s2) {
        Integer i1=null;
        Integer i2=null;
        try {
            i1 = Integer.parseInt(s1);
        } catch (NumberFormatException e) {

        try {
            i2 = Integer.parseInt(s2);
        } catch (NumberFormatException e) {

        if(i1!=null && i2!=null){
            return i1.compareTo(i2);
            return s1.compareTo(s2);


public static void main(){
String []arr = {"3","2","4","10","11","6","5","8","9","7","jgj","ek"};
Arrays.sort(arr, new CustomComparator());
        for(String s:arr){
            System.out.print(s+"  ");

Sorting and Searching, The sorting problem is to rearrange an array of items in ascending order. The following code mimics this process in a Java method that sorts strings in an array: public static void sort(String[] a) { int n = a.length; for (int i = 1; i < n; i++) and whose reverse Watson-Crick complement appears in the other. Converting String Array to an Integer Array. so basically user enters a sequence from an scanner input. 12, 3, 4, etc. It can be of any length long and it has to be integers.

Java Arrays, Sorting Arrays of Objects of the class MyClass , which symbolizes a class you have created yourself. The previous Java array example created an array of int which is a primitive data type. The Java programming language contains a shortcut for instantiating arrays of primitive types and strings. I want to create a date array and sort it. This is how I was able to do it but this is not what I required. java.text.SimpleDateFormat sdf = new java.text.SimpleDateFormat("dd-MM-yyyy"); java.

How to Find all Pairs in Array of Integers Whose sum , You should at your best on data-structures like an array, linked list, and Arrays; /** * Java Program to find pairs on integer array whose sum is equal to k A more efficient in-place solution would be to sort the array and use two each sum that you have to compute can be represented as a 31 bit integer. In the sortDescending() method we called the overloaded Collections.sort() method to sort the elements in descending order. This version of Collections.sort() accepts the ArrayList object as the first parameter and a Comparator object that theCollections.reverseOrder() method returns as the second parameter.

Java String Array Examples, Here are some examples on how to use String Array in Java. When we have an array of Strings, it is usually common to have a scenario public static void bubbleSort( String[] arr ) { int j = 0; String tmp; boolean sorted = false; while We initialize each element with a String Array that represents a pair of  java.util.Collections.sort() method is present in java.util.Collections class. It is used to sort the elements present in the specified list of Collection in ascending order. It works similar to java.util.Arrays.sort() method but it is better then as it can sort the elements of Array as well as linked list, queue and many more present in it.

  • If you have strings you want to use as numbers, why don't you convert them to an appropriate, numeric type? Then when you're done with using them as numbers, you can always convert them back to strings again... If you want to go the harder route: create a custom Comparator<String> for the purpose...
  • Cant you loop through the array and convert them into ints
  • I read about Comparators, but what is the most efficient way? Compator or simple converting?
  • Read my comment below: it will always be more efficient to convert the whole array first because all sorting algorithms take more comparisons than the size of the list.
  • If you are using String array to sort by Arrays.sort() then there is no way left for you to sort them as number.Because you can not even change equals method and anyway after all number array is the best choice.
  • Just a suggestion: perhaps Integer.toString(myIntArray[i]) would illustrate the type conversion more explicitly than "" + myIntArray[i]
  • I like the succinctness of this solution, but there is a bit of a performance hit compared to pre-converting the array because we convert a String to an int every time we compare: since the number of comparisons is always greater than the size of the list, we are doing more conversions than necessary. I don't know if performance is an issue for OP but worth bearing in mind.
  • True, though I would often use a quick and elegant solution over a more thoroughly performance-tuned one until I know there is a need for the latter.