3

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

2 Answers 2

5

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.

Sign up to request clarification or add additional context in comments.

Comments

1

If you're able to extract the roman numerals in the strings you could use a roman numeral parser in your Comparator. Replace the roman numerals with arabic numerals and then compare the strings. You'll have to left-pad the arabic numerals with zeroes so they all have the same number of digits. Here's an example of such a parser in Java at Rosetta Code.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.