Sort SparseArray in Android

How can I sort android.util.SparseArray ? For instance. I have a SparseArray with:
1 - 2,33
5 - 1,5
Result:
5 - 1,5
1 - 2,33

Thanks!!!

- EDITED

I used the card. Thanks for the help.

+6
source share
6 answers

It is unclear whether you requested an order sorted by value or value ...

so simple note:

Binary search only works on sorted data, and SparseArray uses a binary search for its sorted (!) Array of keys according to the source . Thus, the ARE keys are already sorted and will not take a different order, for example, the order of the values.

+5
source

Use LinkedHashMap if you want to sort the map.

Update:

You can use TreeMap. It saves records sorted by their key (the key must be implemented by Comparable).

+2
source

One minor correction to the @Karussell dispute is that the documentation of valueAt() offers an ordered order (by keys):

[...] valueAt(0) will return the value associated with the smallest key, and valueAt(size()-1) will return the value associated with the smallest key.

A similar description is given for the keyAt() method.

+2
source

Judging by the base source code for SparseArray.java , you cannot do this by calling the method. All SpareArray are two Java language arrays, one of int types and one of Object types. These arrays are private instance variables, and you cannot reference them without Reflection (which is dangerous because their names can change). A good solution would be to localize the SpareArray code in your application and add a sort method using regular Java methods, i.e. Array.sort .

0
source

Please check my solution, sorted by keys:

  private static SparseIntArray sFactorsMap = new SparseIntArray(); private static void sortMap() { SparseIntArray sortedSparseIntArray = new SparseIntArray(); while (sFactorsMap.size() > 0) { int min = Integer.MAX_VALUE; for (int i = 0; i < sFactorsMap.size(); i++) { if (sFactorsMap.keyAt(i) <= min) { min = sFactorsMap.keyAt(i); } } sortedSparseIntArray.put(min, sFactorsMap.get(min)); sFactorsMap.removeAt(sFactorsMap.indexOfKey(min)); } sFactorsMap = sortedSparseIntArray; } 
0
source

Collect your keys / values ​​into lists.

  List<Integer>keys = Lists.newArrayList(); List<Integer>vals = Lists.newArrayList(); SparseArray<Integer>arr; for(int i =0; i < arr.size();i++){ keys.add(arr.keyAt(i)); values.add(arr.valueAt(i)); } Collections.sort(keys);// sort Collections.sort(vals); // then fill your array again. arr.clear(); //... arr.put() 
-5
source

Source: https://habr.com/ru/post/923954/


All Articles