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)
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));
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With