How To Get Guaranteed Order of SharedPreferences.getStringSet()

Arief Bayu Purwanto
Bits and pieces of my mind
2 min readMar 22, 2020

There times when we need to store simple list of strings in settings preferences, be it notification strings, list of short notes, etc. For that, Android has provided as with a method in SharedPreferences.getStringSet(). Looking at the documentation, there is this little but incredibly important note:

Note that you must not modify the set instance returned by this call. The consistency of the stored data is not guaranteed if you do, nor is your ability to modify the instance at all.

Working With getStringSet()

Now that we have the method, let’s see what we can do with it.

To store string set, we do the following lines:

And to get the list, we wrote these:

Testing The Codes

I created little snippet to test saving 10 strings

Here’s what the log looks like

Notice that the fetching and ordering order are all jumbled. This is because of the underlying characteristics of set. If you look closer, I did use HashSet in the process. One might argue that I should have used LinkedHashSet, a direct extend of HashSet, because as the documentation said, HashSet doesn’t guarantee order.

It makes no guarantees as to the iteration order of the set; in particular, it does not guarantee that the order will remain constant over time.

While LinkedHashSet told us:

This implementation differs from HashSet in that it maintains a doubly-linked list running through all of its entries. This linked list defines the iteration ordering, which is the order in which elements were inserted into the set (insertion-order).

So, changing all HashSet into LinkedHashSet should remedy the situation, right? Not so fast! Apparently, even the underlying codes of getStringSet() are also using HashSet as evidently seen in the repository:

What about the mMap variable? it was declared like this:

private Map<String, Object> mMap = new HashMap<>();

The Solution?

Simple: don’t use HashMap😅

To do that, I used JSONArray in the form or ArrayList:

And change every implementation of HashSet into StringSettingList and save the content to SharedPreferences using putString() instead of putStringSet():

In conclusion, how to get guaranteed order of SharedPreferences.getStringSet() is by not using it😅. Do you guys have any other recommendation? Please do share with me.

--

--

Arief Bayu Purwanto
Bits and pieces of my mind

Project Leader at AkuPeduli.org | Mozilla Representative | @bloggerngalam | @ariefbayu | blogging at https://ariefbayu.dev