简体   繁体   中英

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:

c ar, do c tor, basi c

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM