Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java: Sort an array according to matching string / pattern [closed]

I need to sort an array in which the matching items comes up and others will goes down.

For Ex. I have an Array : [ z , asxdf , abasdf , abcasdf , b , bc , bcd , c ] What I need is when I pass a KeyWord suppose "b" , then it should sort the given array in which all the string starting with b.. will come first and the rest after that. Which will generate final output : [ b , bc , bcd , z , c , .. (rest).]

If it is possible using comparator in Java ?

String keyWord = "b";
String[] s = {"z", "asxdf", "abasdf", "abcasdf", "b", "bc", "bcd", "c"};
Arrays.sort(s, new Comparator<String>() {

    @Override
    public int compare(String o1, String o2) {

            //Code to sort array according to need

    }
});
System.out.println(Arrays.toString(s));

Result -> [ b , bc , bcd , z , c , ...]

(I may use List instead of Array, or any other if it help me solve this)

like image 218
Shreyas Dave Avatar asked Jun 25 '13 05:06

Shreyas Dave


1 Answers

Answering the question whether is possible to do it with a Comparator, the answer is yes: you just need to create a new Comparator class instead of creating an anonymous Comparator, like this:

    class MyComparator implements Comparator<String> {

        private final String keyWord;

        MyComparator(String keyWord) {
            this.keyWord = keyWord;
        }

        @Override
        public int compare(String o1, String o2) {

            if(o1.startsWith(keyWord)) {
                return o2.startsWith(keyWord)? o1.compareTo(o2): -1;
            } else {
                return o2.startsWith(keyWord)? 1: o1.compareTo(o2); 
            }
        }
    }

and then use that comparator in your code:

    String keyWord = "b";
    String[] s = {"z", "asxdf", "abasdf", "abcasdf", "b", "bc", "bcd", "c"};
    Arrays.sort(s, new MyComparator(keyWord));
    System.out.println(Arrays.toString(s));
like image 190
morgano Avatar answered Sep 18 '22 23:09

morgano