How to order an array of String with numerical data

1

Some time ago I have this doubt which says, how can I compare several String respecting the numerical data that may contain as in the re-naming of files of any folder. I was investigating, and why when comparing the Strings with this type of data is different from what one expects, it is because they are ordered in a lexicographical way (Character by character) but still I can not find a way to solve it.

Also I would like to say that I can not just put all the characters that are not numbers and sort them, because in the Strings that I am using they can have numbers in between.

This is an example of my problem

String[] nombres = {"hola 1", "hola 5", "hola 15", "hola 2};

    //Ordena el array
    Arrays.sort(nombres);

    //Array ya ordenado
    for (String i : nombres) {
        System.out.print(i + ", ");
    }

The result I get is:

  

hello 1, hello 15, hello 2, hello 5

The result I want is:

  

hello 1, hello 2, hello 5, hello 15

I would like to know if there is a method to solve my problem.

    
asked by Getsuga Tenshou 07.02.2018 в 19:44
source

3 answers

0

It would be something like this:

    import java.util.Arrays;
    import java.util.List;
    import java.util.Comparator;
    import java.util.Collections;

    public class MyClass {
     public static void main(String[] args) {
     List<String> strings = Arrays.asList("hola 1", "hola 5", "hola 15", "hola 2");
     Collections.sort(strings, new Comparator<String>() {
        public int compare(String o1, String o2) {
            return extractInt(o1) - extractInt(o2);
        }

        int extractInt(String s) {
            String num = s.replaceAll("\D", "");
            return num.isEmpty() ? 0 : Integer.parseInt(num);
        }
    });
    System.out.println(strings);
    }
}

Result:

[hello 1, hello 2, hello 5, hello 15]

Source: Here

    
answered by 07.02.2018 / 23:21
source
0

You will have to create a custom comparator, here is one: link

Once you have it in your project, you just have to use it like this:

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

The output for your example is as follows:

  

hello 1, hello 2, hello 5, hello 15,

    
answered by 07.02.2018 в 23:13
0

Actually the result you get when ordering the original array by:

Arrays.sort(nombres);

is

  

hello 1, hello 15, hello 2, hello 5

Because you are actually ordering a String, in this case try to sort the ones that start with hello 1, (hello 1, hello 15), and so on:

For example if you had as array:

String[] nombres = {"hola 1", "hola 3", "hola 5", "hola 15", "hola 2","hola 1222", "hola 1999"};    

It would be ordered in this way:

  

Hello 1, Hello 1222, Hello 15, Hello 1999, Hello 2, Hello 3, Hello 5

The sorting of the characters must be done as if they were integers.

This would be a method using a class that implements Comparator, this would be the class:

    static class ColumnComparator implements Comparator {
    int columnToSort;
    ColumnComparator(int columnToSort) {
        this.columnToSort = columnToSort;
    }
    //sobreescribe metodo compare
    public int compare(Object o1, Object o2) {
        String[] row1 = (String[]) o1;
        String[] row2 = (String[]) o2;

                int res = Integer.parseInt(row1[0].toString()) -  Integer.parseInt(row2[0].toString());         
                return res;
    }
}

And you would perform the ordering in this way:

        String[] nombres = {"hola 1", "hola 5", "hola 15", "hola 2"};    

        String[][] nombresAOrdenar = new String[nombres.length][2]; 

        for (int i=0; i< nombres.length ; i++) {
            //Extrae valores de array, el numero será la columna a ordenar.
            String[] parts = nombres[i].split(" ");
            nombresAOrdenar[i][0] =  parts[1];
            nombresAOrdenar[i][1] =  parts[0];        
        }  

        //Ordena valores por columna 1 (indice 0)
        Arrays.sort(nombresAOrdenar, new ColumnComparator(0));

       //Agrega valores ordenados a array original 
       for (int j=0; j< nombres.length ; j++) {           
            nombres[j] = nombresAOrdenar[j][1].toString() + " "+ nombresAOrdenar[j][0].toString();
       }  

Having ordered the array you can now print the values:

   //Imprime valores de Array ya ordenado
   for (String nombre : nombres) {
        System.out.print(nombre + ", ");
   }

To have as output:

hola 1, hola 2, hola 5, hola 15

This is a online demo of the above.

    
answered by 07.02.2018 в 23:56