Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

266
Visualizações
Sort Java ArrayList with Letters before numbers

I am currently passing in an ArrayList to populate the titles of a TabLayout in Android. The elements in the array are strings: ["RCP", "RYL", "1", "2", "3", "4", "5", "6"]. Yet, not necessarily in that order.

I would like the list to be returned with the Letter elements first (alphabetically) and then integers rising, incrementally.

I have tried using the Collections.sort method, but this returns a list the rises numerically and then adds the "R" strings last: ["1", "2", "3", "4", "5", "6", "RCP", "RYL"]

To clarify, I would like to sort my ArrayList, so that it returns ["RCP", "RYL", "1", "2", "3", "4", "5", "6"] It also needs to be flexible, as the titles of the "R", strings, are likely to change.

Thanks

about 4 years ago · Santiago Trujillo
2 Respostas
Responde à pergunta

0

There is an overload for Collections.sort which will take in a Comparator, which will allow you to define the sort order for your items. In this case, all you have to do is define your own implementation of the Comparator interface which does as you please.

about 4 years ago · Santiago Trujillo Relatório

0

If you want to give priority to strings that represents numbers over strings that do not, you should consider writing your own Comparator and pass it to the Collections.sort method.

This is a simple approach to your problem: check if any of the strings is a number, if so, give priority to the string that is not a number. If both are numbers or strings, use string's compareTo method.

Hope it helps.

public class Main {

    private static int customCompare(String a, String b) {
        return isThereAnyNumber(a, b)
                ? isNumber(a) ? 1 : -1
                : a.compareTo(b);
    }

    private static boolean isThereAnyNumber(String a, String b) {
        return isNumber(a) || isNumber(b);
    }

    private static boolean isNumber(String s) {
        return s.matches("[-+]?\\d*\\.?\\d+");
    }

    public static void main(String[] args) {
        List<String> list = Arrays.asList("RCP", "RYL", "1", "2", "3", "4", "5", "6");
        Collections.sort(list, Main::customCompare);
        System.out.println(list);
    }
}

UPDATE

You can use an anonymous inner class that implements the Comparator interface in case you're not using Java 8.

public class Main {

    public static void main(String[] args) {
        List<String> list = Arrays.asList("RCP", "RYL", "1", "2", "3", "4", "5", "6");
        Collections.sort(list, new Comparator<String>() {
            private boolean isThereAnyNumber(String a, String b) {
                return isNumber(a) || isNumber(b);
            }

            private boolean isNumber(String s) {
                return s.matches("[-+]?\\d*\\.?\\d+");
            }

            @Override
            public int compare(String a, String b) {
                return isThereAnyNumber(a, b)
                        ? isNumber(a) ? 1 : -1
                        : a.compareTo(b);
            }
        });
        System.out.println(list);
    }
}
about 4 years ago · Santiago Trujillo Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda