如何在未知名称/ID的情况下遍历Firestore所有集合?
Firestore 获取所有顶层集合内容的修复方案
你的代码目前只能拿到第一个顶层集合,核心问题是只调用了一次iterator.next(),没有遍历所有集合——原来的if (iterator.hasNext())只会处理第一个集合,后面的集合完全没被处理。
另外你的deviceKeyCurrencyListMap逻辑也存在问题:每次添加时直接把同一个currencyList对象存进去,会导致所有key对应的列表都是同一个实例;而且存在重复添加数据的情况(先add一次,后面又判断contains再add一次)。
以下是修正后的代码:
public List<Currency> getRemindedCurrencies() throws ExecutionException, InterruptedException { String key = "deviceKey"; Firestore db = FirestoreClient.getFirestore(); Iterable<CollectionReference> collectionReferences = db.listCollections(); Iterator<CollectionReference> iterator = collectionReferences.iterator(); List<Currency> currencyList = new ArrayList<>(); HashMap<String, List<Currency>> deviceKeyCurrencyListMap = new HashMap<>(); // 用while循环遍历所有顶层集合,而非仅处理第一个 while (iterator.hasNext()) { CollectionReference next = iterator.next(); for (Currencies currencies : Currencies.values()) { DocumentReference document = next.document(currencies.name().toLowerCase() + "-reminder"); ApiFuture<DocumentSnapshot> snapshotApiFuture = document.get(); DocumentSnapshot documentSnapshot = snapshotApiFuture.get(); if (documentSnapshot.exists()) { Currency currency = documentSnapshot.toObject(Currency.class); currencyList.add(currency); String keyVal = documentSnapshot.getData().get(key).toString(); // 自动创建不存在的列表,避免重复或覆盖问题 deviceKeyCurrencyListMap.computeIfAbsent(keyVal, k -> new ArrayList<>()) .add(currency); } } } return currencyList; }
关键修改点:
- 将
if (iterator.hasNext())替换为while (iterator.hasNext()),确保遍历所有顶层集合 - 使用
computeIfAbsent处理deviceKeyCurrencyListMap,避免重复创建列表或覆盖已有数据 - 提取
Currency对象,避免重复调用toObject,同时解决原代码中重复添加数据的问题
内容的提问来源于stack exchange,提问作者Halil Sahin
相关产品推荐
相关产品推荐

