我通过 JSON 获取一些数据,并将其存储在 Hashmap 映射 中,例如map.put(KEY_TITLE, parser.getString("title")) ,然后将 map 添加到 ArrayList> bookList 中。这显示在 ListView 中,其中 bookList 作为适配器的源。此外,我还将 map 的所有图书信息(标题、作者、出版日期)存储在 Arraylist arrTitles、arrAuthors、arrDates 中,因为我需要将这些值传递到下一个 Activity 。我的问题是,当我使用比较器根据标题对 bookList 进行排序时,bookList 就会得到很好的排序。然而,我想根据 bookList 的新排序对我的 arrTitles、arrAuthors 和 arrDates 进行排序,以便我的 arrTitles.getItem(position) 将正确的值发送到下一个 Activity 。知道我该怎么做吗?下面是 hashmap、arraylist、onItemClick 和比较器代码:
for (int i = 0; i < json.Length(); i++) {
HashMap<String, String> map = new HashMap<String, String>();
// adding each child node to HashMap key => value
map.put(KEY_ID, json.getString("id"));
map.put(KEY_TITLE, json.getString("title"));
map.put(KEY_AUTHOR, json.getString("author"));
map.put(KEY_DATE, json.getString("date"));
arrTitles.add(json.getString("title");
arrAuthors.add(json.getString("author");
arrDates.add(json.getString("date");
//add map to ArrayList
booksList.add(map);
}
list=(ListView)findViewById(R.id.list);
Collections.sort(booksList, mapComparator);
adapter=new LazyAdapter(this, booksList);
list.setAdapter(adapter);
// Click event for single list row
list.setOnItemClickListener(new OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
Intent intent = new Intent(this, editList.class);
intent.putExtra("title", arrTitles.getItem(position));
intent.putExtra("date", arrDates.getItem(position));
startActivity(intent);
}
});
}
public Comparator<Map<String, String>> mapComparator = new Comparator<Map<String, String>>() {
public int compare(Map<String, String> m1, Map<String, String> m2) {
return m1.get(KEY_TITLE).compareTo(m2.get(KEY_TITLE));
}
};
最佳答案
是的,使用新代码看起来相当简单:只需在对 map 列表进行排序后创建单独的列表即可:
// This loop looks wrong at the moment - you're not using i
for (int i = 0; i < json.Length(); i++) {
HashMap<String, String> map = new HashMap<String, String>();
// adding each child node to HashMap key => value
map.put(KEY_ID, json.getString("id"));
map.put(KEY_TITLE, json.getString("title"));
map.put(KEY_AUTHOR, json.getString("author"));
map.put(KEY_DATE, json.getString("date"));
booksList.add(map);
}
for (Map<String, String> map : booksList) {
arrTitles.add(map.get(KEY_TITLE));
arrAuthors.add(map.get(KEY_AUTHOR));
arrDates.add(map.get(KEY_DATE));
}
请注意,我仍然强烈建议创建 Book
类来存储数据,而不是使用 Map<String, String>
用固定键。我怀疑,在代码的其他地方使用会简单得多。
关于java - 如何对包含已通过比较器排序的 ArrayList<HashMap<String, String>> 元素的 ArrayList<String> 进行排序?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21570517/