2

If its duplicate question please suggest me that link,

my code is

 public static void main(String[] args) {
      String name ="h498y948759hrh98A722hjDF94yugerTEr892ur48y";
      char[] arr= name.toCharArray();
      Arrays.sort(arr);
      System.out.println(arr);
}

and result is

 222444457788888999999ADEFTeghhhhjrrrruuyyy

now i want to chnage the sequence of this sorting like ADEFT222444457788888999999eghhhhjrrrruuyyy or eghhhhjrrrruuyyy222444457788888999999ADEFT

so question is how can i change this sequence? and if this is wrong way of sorting then please tell me right one.

Thanks

2 Answers 2

4

You can create your own Comparator class/object and pass it to Arrays.sort(). Unfortunately, you also need to convert the elements to Character.

However, perhaps the most general way is to see each character as a String and use a Collator, as in the following example:

    //  Rules separated in 3 parts only for convenience
    String rules1= "< A < B < C < D < E < F < G < H < I < J < K < L < M < N < O < P < Q < R < S < T < U < V < W < X < Y < Z" ;
    String rules2= "< a < b < c < d < e < f < g < h < i < j < k < l < m < n < o < p < q < r < s < t < u < v < w < x < y < z" ;
    String rules3= "< 0 < 1 < 2 < 3 < 4 < 5 < 6 < 7 < 8 < 9" ;
    RuleBasedCollator collator= new RuleBasedCollator(rules1+rules2+rules3) ;

    String input= "h498y948759hrh98A722hjDF94yugerTEr892ur48y" ;

    //  Bulk of the job done here
    String[] arr= input.split("") ;
    Arrays.sort(arr,1,arr.length,collator);

    //  Join back in a single string for presentation
    StringBuilder sb= new StringBuilder() ;
    for(String e: arr )
        sb.append( e );
    System.out.println(sb);

Output is

    ADEFTeghhhhjrrrruuyyy222444457788888999999

Changing only collation rules to

    String rules1= "< 0 < 1 < 2 < 3 < 4 < 5 < 6 < 7 < 8 < 9" ;
    String rules2= "< A,a < B,b < C,c < D,d < E,e < F,f < G,g < H,h < I,i < J,j < K,k < L,l < M,m < N,n < O,o < P,p < Q,q < R,r < S,s < T,t < U,u < V,v < W,w < X,x < Y,y < Z,z" ;
    RuleBasedCollator collator= new RuleBasedCollator(rules1+rules2) ;

Output is

    222444457788888999999ADEeFghhhhjrrrrTuuyyy

The main advantage of Collators is that they allow to sort multi-character Strings according to their internal rules. In fact, this is their main use case.

Pretty powerful, eh? (Yes, I'm Canadian in case you didn't guess :-) )

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

5 Comments

Yes, though you'd have to convert the char[] to a Character[] first, since Arrays.sort(char[]) does not have a version that uses a Comparator (since Comparator cannot work with primitive types).
+1 for using a collation-based approach; it's been a long time since I've seen any use of a collator. Also, I must be missing something; I don't see anything in your answer (except the last sentence) that might hint at your being Canadian, unless "pretty powerful, eh" is supposed to be a Canadian idiom or something. :-P (I'm a New Zealander, by the way.)
@ChrisJester-Young According to popular culture we tend to end each sentence in "eh?". But we take it with humor, eh?
@VeronicaCornejo Lol. I'm sure Kiwis and Brits end sentences with "eh" pretty frequently too, so it wouldn't be unusual for me to hear, eh? :-P
@VeronicaCornejo can the collator be used to sort alpha numerically?This might not be part of what OP was expecting to be answered but I believe this is a limitation of using a collator based approach?
3

I've written some sample to demonstrate the Comparator concept. It requires Guava:

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

import com.google.common.collect.ComparisonChain;
import com.google.common.primitives.Chars;

public class Test {
    private enum Comparators implements Comparator<Character> {
        UPPER_DIGIT_LOWER {
            @Override
            int compare(char lhs, char rhs) {
                return ComparisonChain.start()
                        .compareTrueFirst(Character.isUpperCase(lhs), Character.isUpperCase(rhs))
                        .compareTrueFirst(Character.isDigit(lhs), Character.isDigit(rhs))
                        .compareTrueFirst(Character.isLowerCase(lhs), Character.isLowerCase(rhs))
                        .compare(lhs, rhs)
                        .result();
            }
        },
        LOWER_DIGIT_UPPER {
            @Override
            int compare(char lhs, char rhs) {
                return ComparisonChain.start()
                        .compareTrueFirst(Character.isLowerCase(lhs), Character.isLowerCase(rhs))
                        .compareTrueFirst(Character.isDigit(lhs), Character.isDigit(rhs))
                        .compareTrueFirst(Character.isUpperCase(lhs), Character.isUpperCase(rhs))
                        .compare(lhs, rhs)
                        .result();
            }
        };

        @Override
        public int compare(Character lhs, Character rhs) {
            return compare(lhs.charValue(), rhs.charValue());
        }

        abstract int compare(char lhs, char rhs);
    }

    private static String sortChars(String str, Comparator<Character> cmp) {
        List<Character> chars = Chars.asList(str.toCharArray());
        Collections.sort(chars, cmp);
        return new String(Chars.toArray(chars));
    }

    public static void main(String[] args) {
        String name = "h498y948759hrh98A722hjDF94yugerTEr892ur48y";
        System.out.println(sortChars(name, Comparators.UPPER_DIGIT_LOWER));
        System.out.println(sortChars(name, Comparators.LOWER_DIGIT_UPPER));
    }
}

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.