【问题标题】:How to sort HashMap<String,ArrayList> in Android?如何在 Android 中对 HashMap<String,ArrayList> 进行排序?
【发布时间】:2015-03-20 20:52:25
【问题描述】:

HashMap&lt;String,ArrrayList&lt;String&gt;&gt;如何排序?

我正在从电话联系人中获取联系人姓名,例如:

"String name = cur.getString(cur.getColumnIndex(ContactsContract.Contacts.DISPLAY_NAME));"

并将其存储到一个HashMap&lt;String,ArrayList&lt;String&gt;&gt; 中。但是我得到的所有联系人都是未排序的。

我可以知道如何按字母顺序对这些联系人进行排序,以便我可以按排序顺序显示列表视图吗?

【问题讨论】:

  • 您在发布问题之前是否搜索过此主题?
  • 我搜索过,但我只知道如何解析 HashMap 或 HashMap
  • 两天以来我一直坚持这一点
  • HashMap。 ArrayList 是什么?更多字符串?
  • 只需使用 Comparator 即可....

标签: android collections


【解决方案1】:

您可以从已排序的数据库中检索数据。只需使用

String orderBy =  ContactsContract.Contacts.DISPLAY_NAME + " DESC";

在您的查询中。之后,通常当您需要使用 HashMap 并且已经对数据进行了排序时,则使用HashMap + ArrayList。在 HashMap 中保留普通的键值对,在 ArrayList 中保留排序值(如果您已经对数据进行了排序,则在读取时将其添加到 ArrayList,无需再次排序)。

如果您需要对 HashMap 中的值 ArrayList 进行排序,您可以使用:

Collections.sort(yourArrayList);

【讨论】:

    【解决方案2】:

    使用下面的类并将数据列表传递给它。它会给你新的排序列表。

    public class CompareApp implements Comparator<AppDetails> {
    
    private List<AppDetails> apps = new ArrayList<AppDetails>();
    
    Context context;
    
    public CompareApp(String str,List<AppDetails> apps, Context context) {
        this.apps = apps;
        this.context = context;
    
        Collections.sort(this.apps, this);
    }
    
    @Override
    public int compare(AppDetails lhs, AppDetails rhs) {
        // TODO Auto-generated method stub
        return lhs.label.toUpperCase().compareTo(rhs.label.toUpperCase());
    }
    

    }

    【讨论】:

    • AppDetails 是一个泛型类
    • 公共类 AppDetails { 公共字符串标签;公共字符串包名;公共可绘制图标; }
    【解决方案3】:

    我使用以下代码以字符串名称的升序获取联系人,如下所示:

    public void getAllContacts(ContentResolver cr) {
    
    
            Cursor phones = cr.query(
                    ContactsContract.CommonDataKinds.Phone.CONTENT_URI, null, null,
                    null, Phone.DISPLAY_NAME + " ASC");
    
            while (phones.moveToNext()) {
                String name = phones
                        .getString(phones
                                .getColumnIndex(ContactsContract.CommonDataKinds.Phone.DISPLAY_NAME));
                String phoneNumber = phones
                        .getString(phones
                                .getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER));
                name1.add(name);
                phno1.add(phoneNumber);
            } 
    
    
            phones.close();
        } 
    

    Code for reference

    希望这是你需要的。

    【讨论】:

    • 还有一个问题。你能告诉我如何在我的自定义适配器中为列表视图添加搜索选项
    • @User_B 你可以在你的ListView中添加一个EditText组件作为HeaderView。
    • 你有sn-p吗
    • 只需将编辑文本放在列表视图组件上方即可
    猜你喜欢
    • 1970-01-01
    • 2013-09-09
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-03-16
    • 1970-01-01
    • 1970-01-01
    • 2017-06-01
    相关资源
    最近更新 更多