【问题标题】:Compare HashMap and List and return value比较HashMap和List并返回值
【发布时间】:2025-12-30 15:45:07
【问题描述】:

我已将用户手机中的联系人存储在 Map 中,其中 phoneNumbers 作为键,contactNames 作为值。此外,当用户注册时,我检索了存储在 Firebase 中的 phone_number。在下面的方法中,我正在比较这张地图和列表。

public static Collection contains(Map map, List list) {

    Collection<String> keys = map.keySet();
    Set<String> result = new HashSet<>();
    for (String listItem:list) {
        if (keys.contains(listItem)){
            result.add(listItem);
        }
    }
    return result;  
}

当 Map 的键匹配时,从 Firebase 检索到 phone_number,我想获取与之关联的值。请问我该怎么做?

【问题讨论】:

    标签: android list hashmap


    【解决方案1】:

    考虑使用 HashMap

       //Considering this stored contacts
        Map<String, String> contactsStored = new HashMap<>();
        contactsStored.put("999 999 999", "Anne");
        contactsStored.put("000 000 000", "Jonh");
    
        //and this firebase data               
        List<String> firebaseNumbers =  new ArrayList<>();
        firebaseNumbers.add("000 000 000");
    
        for (String firebaseNumberKey : firebaseNumbers) {
            contactsStored.get(firebaseNumberKey);
        }
    

    【讨论】:

    • 工作!!谢谢