how to not sort a HashSet values and allow duplicate?

1.4k views Asked by At

I am working on Android Project where I want to save an arrayList values into sharedpreferences

I don't want to sort or remove duplicate values from the list

I want the exact data in arrayList to be saved in HashSet

for example this is my arrayList Output:

D/waitingList﹕ [a, b, c, a, a, aa, cc]

but when I save it inside HashSet it sort

D/setWaiting﹕ [aa, a, b, cc, c]

and at sharedpreferences xml file like this

<?xml version='1.0' encoding='utf-8' standalone='yes' ?>
<map>
    <int name="count_games" value="0" />
    <set name="setCurrent" />
    <set name="setWaiting">
        <string>a</string>
        <string>aa</string>
        <string>b</string>
        <string>c</string>
        <string>cc</string>
    </set>
</map>

I have to keep everything sorted as in the arrayList

this is my code:

public void saveArrayList(Context mContext, ArrayList<String> currentList, ArrayList<String> waitingList, int count)
    {
        SharedPreferences pref = PreferenceManager.getDefaultSharedPreferences(mContext);
        SharedPreferences.Editor edit = pref.edit();

        HashSet<String> setCurrent = new HashSet<String>();
        setCurrent.addAll(currentList);
        Log.d("setCurrent",setCurrent.toString());
        Log.d("currentList",currentList.toString());

        HashSet<String> setWaiting = new HashSet<String>();
        setWaiting.addAll(waitingList);
        Log.d("setWaiting",setWaiting.toString());
        Log.d("waitingList",waitingList.toString());


        edit.putStringSet("setWaiting", setWaiting);
        edit.putStringSet("setCurrent", setCurrent);

        edit.putInt("count_games", count);

        edit.commit();


    }
1

There are 1 answers

4
barunsthakur On BEST ANSWER

By definition, a Set cannot have duplicate values so you cannot do what you want.

Also HashSet doesn't preserve the order, if you want ordered set you can use LinkedHashSet which preserves insertion order.