Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Custom string sorting in java

Tags:

java

sorting

i have wrote a java program in java to sort strings alphabetically . The problem is when it sorts string having roman numerals it treats it as character and sorts accordingly

import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
public class SampleCustomSortApp
{
    @SuppressWarnings("unchecked")
    public static void main(String[] args)
    {
        ArrayList<String> titles =new ArrayList();
        titles.add("java");
        titles.add("J-IV");
        titles.add("A-V");
        titles.add("J-V");
        titles.add("J-IX");
        titles.add("J-XX");
        titles.add("J-X");
        titles.add("J-I");
        titles.add("J-II");

        titles.add("datawarehouse");
        titles.add("oracledba");
        System.out.println("Before Sorting Elements Are :"+titles+"\n");
        Collections.sort(titles, new MyCustomCompator());
        System.out.println("After Sorting Elements Are :"+titles);
    }
}
class MyCustomCompator implements Comparator
{
    public int compare(Object s1,Object s2)
    {
        String one = (String)s1;
        String two = (String)s2;
        /* for ascending order */
        if(one.compareTo(two)>0){
            return 1;
        }else{
            return -1;
        }
    }
}

Actual Output

Before Sorting Elements Are :[java, J-IV, A-V, J-V, J-IX, J-XX, J-X, J-I, J-II, datawarehouse, oracledba]

After Sorting Elements Are :[A-V, J-I, J-II, J-IV, J-IX, J-V, J-X, J-XX, datawarehouse, java, oracledba]

Desired Output

Before Sorting Elements Are :[java, J-IV, A-V, J-V, J-IX, J-XX, J-X, J-I, J-II, datawarehouse, oracledba]

After Sorting Elements Are :[A-V, J-I, J-II, J-IV,  J-V,J-IX, J-X, J-XX, datawarehouse, java, oracledba]

should i use regex expression to compare the strings. can some tell me the solution

like image 904
Vivek Shankar Avatar asked Dec 05 '25 17:12

Vivek Shankar


1 Answers

You definitely need your own Comparator which appropriately parses the Roman numerals. The job of parsing has (naturally) already been solved, so you just need to split your strings into alphabetic and numeral parts. See here for an example of Roman numeral parsing code.

like image 183
Marko Topolnik Avatar answered Dec 08 '25 05:12

Marko Topolnik



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!