Emil Heraña Emil Heraña - 3 months ago 15
Android Question

How to ignore first Word when Sorting

I have a

List
of
Strings
and I want to sort them:

ICD10DatabaseHandler icd10Helper = new ICD10DatabaseHandler(getActivity());
icd10Helper.open();
List<Strings> icd10Favorites = icd10Helper.getFavoriteIcd10Tags();
Collections.sort(icd10Favorites);
icd10Helper.close();
return true;


My problem is my
List
have a
id
before the
description
and what I want to produce is a sort of the the
List
ignoring the first word (
id
) of the element.

Actual output

A000 Cholera due to Vibrio cholerae 01
A010 Typhoid fever with heart involvement
A012 Paratyphoid fever B


Desired Output:

A000 Cholera due to Vibrio cholerae 01
A012 Paratyphoid fever B
A010 Typhoid fever with heart involvement

Answer

If you cannot use java8, you need to define your own Comparator, for example:

class MyComparator<T> implements Comparator<String> {
    private static String getDescription(String s) {
        // get all String after CODE
        String[] all = s.split(" ", 2);

        // if there is some content
        if (all.length >= 2) 
            // get it in LOWER CASE
            return all[1].toLowerCase();
        else 
            return "";
    }

    public int compare(String s0, String s1) {
        return getDescription(s0).compareTo(getDescription(s1));
    }

}

USE

Collections.sort(elements, new MyComparator<String>());

NOTE: if you must use several times, create an instance instead instantiating on the fly


TEST IT

public static void main(String[] args) {
    System.out.println("BEFORE SORTING");
    printList(elements);

    Collections.sort(elements, new MyComparator<String>());

    System.out.println("\nAFTER SORTING");
    printList(elements);
}

private static void printList(List<String> l) {
    for (String s : elements) {
        System.out.println(s);
    }

}

RESULTS:

BEFORE SORTING
A012 Paratyphoid fever B
A010 Typhoid fever with heart involvement
A000 Cholera due to Vibrio cholerae 01

AFTER SORTING
A000 Cholera due to Vibrio cholerae 01
A012 Paratyphoid fever B
A010 Typhoid fever with heart involvement