Search code examples
javaandroidlistviewandroid-studioalphabetical

ListView in alphabetical order without Comparable


I'm trying to put this ListView in an alphabetical order by value of WORDS column. I've already read answers on this topic, but nevertheless haven't found any solution. Have I necessarily use Comparable/Comparator?

private ArrayList<HashMap<String, Object>> wordList;
private static final String WORD = "word";
private static final String DEFINITION = "definition";
private static final String NOTES = "notes";
private SimpleAdapter adapter;

ListView listView = (ListView) findViewById(R.id.listView);
final ListView listView2 = (ListView) findViewById(R.id.listView2);
wordList = new ArrayList<>();
HashMap<String, Object> hm;

for (int i = word_counter - 1; i >= 0; i--) {
    hm = new HashMap<>();
            hm.put(WORD, words[i]);
            hm.put(DEFINITION, definitions[i]);
            hm.put(NOTES, notes[i]);
            wordList.add(hm);
    } 

adapter = new SimpleAdapter(this, wordList,
    R.layout.list_item, new String[]{WORD, DEFINITION, NOTES},
    new int[]{R.id.text1, R.id.text2, R.id.text3});

Solution

  • For auto sorting the data use TreeSet. TreeSet is a Collection in which the data you enter into it will be sorted regardless of the order you entered data into it.

        TreeSet ts=new TreeSet();
        for (int i=0;i<words.length;i++)
        {
            ts.add(words[i]+"-|-"+definitions[i]+"-|-"+notes[i]);
        }
        Iterator<String> itr=ts.iterator();
        while(itr.hasNext()){
            System.out.println(itr.next());
        }
    

    The output will be in ascending order. From here, just split the string you get from the TreeSet using "-|-" as parameter for split(). And use each elements as you need.