首页 > 解决方案 > 如何从 Map 中检索值, 对象>

问题描述

我想知道如何从Map<ArrayList<String>, Object>字符串和对象存储为 Array [] 以供用户定义长度的位置检索值。

这是一个例子:

                             int counter=0, n=0;

                              if (dataSnapshot.exists()){

                                for (DataSnapshot ds: dataSnapshot.getChildren()){

                                    loca[counter]= new ArrayList<>();

                                    itemListProduct[n]= new ItemListProduct();
                                    itemListProduct[n]= ds.getValue(ItemListProduct.class);

                                    loca[counter].add(testHeaderlist.get(counter));

                                    System.out.println(ds.child("item_NAME").getValue(String.class));

                                    objectMap.put(loca[counter],itemListProduct[n]);

                                    counter++;
                                }

testHeaderlist是一个ArrayList<String>存储一些字符串的地方。我想以下面的图像方式存储数据:

在此处输入图像描述

所以现在我的问题是如何从“dataList”中检索密钥和对象。从我在列表的前“n”个列表中共享的代码中,对象存储在 dataList 中。

问题是我想检索以在 ExpandableListView 中使用它。loca作为标题和itemListproduct我的值对象。两者都存储在objectMap.

任何人都可以请解决它。谢谢!

标签: javaarrayshashmapsetexpandablelistview

解决方案


ArrayList将 a 作为地图的键是允许的,但不是典型的。要获得,Object您需要执行以下操作:

Object val = map.get(arrayList)

在这里,arrayList 必须ArrayList包含与引用所需对象的键相同顺序的完全相同的字符串。

例子

Map<List<String>, Integer> map = new HashMap<>();
List<String> key = List.of("abc", "efg");

map.put(key, 20);
Integer v = map.get(List.of("efg","abc")); // different key so
                                           // object not found
System.out.println(v); // prints null

v = map.get(List.of("abc", "efg"));
System.out.println(v); // prints 20

您可以通过以下方式获取地图的所有键

Set<List<String>> set = map.keySet();

您还需要阅读HashMapArrayList以了解它们的工作原理。以下将继续替换对象的键list[0]

dataList.put(list[0], object[0]);
dataList.put(list[0], object[1]);
dataList.put(list[0], object[2]);
dataList.put(list[0], object[3]);

完成以上操作后,list[0]只会参考object[3]


推荐阅读