'How to sort array list by specific character?
I need to sort arrayList by order of specific character, for example C. So if there is a word that starts with letter C it will be first, if it has a C in the middle it will be second and if it has C last, the word will be last.
public static void main(String[] args) {
List<String> str = new ArrayList<String>();
str.add("doctor");
str.add("basic");
str.add("car");
}
Output:
car, doctor, basic
Solution 1:[1]
You must create a custom comparator for your needs, take a cue from this piece of code:
public static void main(String[] args) {
List<String> str = new ArrayList<>();
str.add("doctor");
str.add("basic");
str.add("car");
char letter = 'c';
// Compare method returns -1, 0, or 1 to say if it is less than, equal, or greater to the other.
Comparator<String> customComparator = (str1, str2) -> {
if (str1.indexOf(letter) < str2.indexOf(letter))
return -1;
if (str2.indexOf(letter) < str1.indexOf(letter))
return 1;
return 0; // To add other logic
};
Collections.sort(str, customComparator);
}
In the code above a coarse logic is implemented based on your question, you would just need to complete the logic in the custom comparator to manage the specific cases.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | rentox98 |
