在我的应用程序中,我尝试在 listView 中按按字母顺序顺序对名称进行排序.Got从本地数据库成功获取值。可能我知道什么是实现目标的正确方法是什么?我找不到合适的解决方案。请帮帮我。
我的代码在
下面// Declare this
ArrayList < HashMap < String, Object >> Results;
ArrayList < HashMap < String, Object >> ValuesSpeciality;
public CustomAdapterSpecialityActivity adapterCustom;
//get speciality list from local db and show on listview
public void SpecialitiesOnList() {
HashMap < String, Object > temp;
List < TaxonomyObjects > contacts = db.getAllTaxonomy();
for (TaxonomyObjects cn: contacts) {
temp = new HashMap < String, Object > ();
temp.put("provider", "" + cn.getDisplayName());
temp.put("tvTaxonomyCode", "" + cn.getTaxonomyCode());
System.out.println(temp);
ValuesSpeciality.add(temp);
}
//searchResults=originalValuesSpeciality initially
Results = new ArrayList < HashMap < String, Object >> (ValuesSpeciality);
adapterCustom = new CustomAdapterSpecialityActivity(this, R.layout.list_item_service, searchResults);
lv.setAdapter(adapterCustom);
adapterCustom.notifyDataSetChanged();
for (int i = 0; i < adapterCustom.getCount(); i++) {
HashMap < String, Object > hm = (HashMap < String, Object > ) adapterCustom.getItem(i);
hm.put("position", i);
}
}
结果我的Logcat显示了这个
{Code=204D00000X, provider=Neuromusculoskeletal Medicine & OMM}
{Code=204F00000X, provider=Transplant Surgery}
{Code=204R00000X, provider=Electrodiagnostic Medicine}
{Code=207K00000X, provider=Allergy & Immunology}
{Code=204E00000X, provider=Oral & Maxillofacial Surgery}
我尝试显示提供商名称Alphabetically
订单。
答案 0 :(得分:1)
使用此代码 ...
private static HashMap sortByValues(HashMap map) {
List list = new LinkedList(map.entrySet());
// Defined Custom Comparator here
Collections.sort(list, new Comparator() {
public int compare(Object o1, Object o2) {
return ((Comparable) ((Map.Entry) (o1)).getValue())
.compareTo(((Map.Entry) (o2)).getValue());
}
});
// Here I am copying the sorted list in HashMap
// using LinkedHashMap to preserve the insertion order
HashMap sortedHashMap = new LinkedHashMap();
for (Iterator it = list.iterator(); it.hasNext();) {
Map.Entry entry = (Map.Entry) it.next();
sortedHashMap.put(entry.getKey(), entry.getValue());
}
return sortedHashMap;
}
答案 1 :(得分:0)
如果您使用的是本地数据库,那么您可以在TEXT字段上轻松使用order by
,这将得到结果并使用LinkedHashMap
代替HashMap
,您的问题将很容易解决