简体   繁体   中英

Firestore Document does not maintain the order of keys in LinkedHashMap

I have with me a List of Pairs which I insert into a LinkedHashMap and upload it to the Firestore document. However the key order in the Firestore Document does not match that of the LinkedHashMap.

Here's the code:

    Map<String, String> quesMap = new LinkedHashMap<>();
    for(Pair<String, String> pair : quesAnsPairList){
        Log.d(TAG, "adding key : "  + pair.first);
        quesMap.put(pair.first, pair.second);
    }
    for (Map.Entry<String, String> entry : quesMap.entrySet()) {
        String key = entry.getKey();
        String value = entry.getValue();
        Log.d(TAG, key + " found");
    }
    //....
    visitorsCollectionRef.document(visitor_id).set(quesMap);

Unfortunately, you cannot change that order of documents. I see that you are using Strings when ordering. Note, that when strings are ordered, are ordered lexicographically .

Let's take a simple example. For numbers, this is the normal order:

  • 1308
  • 1309
  • 1310
  • 1311

But for strings, this is the normal order:

  • "1308"
  • "1309"
  • "131"
  • "1310"

There is no operator in Cloud Firestore and as far as i know nor in most other databases that allow you to change this behavior. Instead, you will have to modify the data to get the behavior you want. So, store values that are in the order you need them when sorted lexicographically. For numbers you can accomplish that by padding them with zeroes:

  • "0131" //zero added before
  • "0132" //zero added before
  • ......
  • "1308"
  • "1309"
  • "1310"
  • "1311"

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM