D
D
Denis2018-12-28 13:40:19
Java
Denis, 2018-12-28 13:40:19

How to sort numbers to the end of an array?

How can I set sorting so that strings that start with numbers go to the end of the list?
The general sorting rule is - (A-Z, AZ, 0-9)
In order for Russian characters to come first, I use Collator.

Answer the question

In order to leave comments, you need to log in

2 answer(s)
L
longclaps, 2018-12-28
@longclaps

Are you sure you're a programmer ?
ps That's it, figured it out: a real programmer and a fan of the collator. Well if you say so. Here is a minimal example.

package newjavaapplication;

import java.util.Arrays;
import java.text.RuleBasedCollator;
import java.text.ParseException;

public class NewJavaApplication {
    public static void main(String[] args) throws ParseException {
        RuleBasedCollator myCollator = new RuleBasedCollator
                ("< а,А < б,Б < в,В < 0 < 1 < 2");
        String[] ar = {"1", "2", "А", "б", "В"};
        Arrays.sort(ar, myCollator);
        for (String s : ar)
            System.out.println(s);
    }
}

D
Denis, 2018-12-29
@lacredin

You can do it like this. The example is written in kotlin.
This code will put any string that starts with a number below a string that starts with another character.
val russianCollator = Collator.getInstance(Locale("ru", "RU"))

val array = arrayListOf("Ab", "01", "Ba", "Aa", "90")
        val russianCollator = Collator.getInstance(Locale("ru", "RU"))
        val array_2 = array.sortedWith(
                kotlin.Comparator { o1, o2 ->
                    if(o1.firstOrNull()?.isDigit() == true && o2.firstOrNull()?.isDigit() == false) return@Comparator  1
                    if(o1.firstOrNull()?.isDigit() == false && o2.firstOrNull()?.isDigit() == true) return@Comparator  -1
                    russianCollator.compare(o1, o2)
                }
        )

Although, the requirement stated in the description, this code does not correspond, at least, to characters like ! +- and so on. will be first

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question