【问题标题】:ListView in alphabetical order without ComparableListView 按字母顺序排列,没有 Comparable
【发布时间】:2016-08-25 01:15:33
【问题描述】:

我正在尝试按 WORDS 列的值按字母顺序排列此 ListView。我已经阅读了有关此主题的答案,但仍未找到任何解决方案。我必须使用 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});

【问题讨论】:

    标签: java android listview android-studio alphabetical


    【解决方案1】:

    要自动排序数据,请使用 TreeSet。 TreeSet 是一个集合,无论您输入数据的顺序如何,都会对您输入的数据进行排序。

        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());
        }
    

    输出将按升序排列。从这里,只需使用“-|-”作为 split() 的参数,拆分从 TreeSet 获得的字符串。并根据需要使用每个元素。

    【讨论】:

      猜你喜欢
      • 2016-04-05
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多