Reputation: 1246
Lets say I have a list of keys that all contain an Object like this:
2, 4, 5, 9, 11
I need them to be ordered because I want to do something like:
function Object[] getObjectsAfter( int i );
// so 4 would result in an array of objects in the keys 5, 9 and 11
and
function Object[] getObjectsBefore( int i );
// so 4 would result in an array of objects in the keys 2
What collection is best to use in Android? I tried SparseArray and TreeMap, but I can't find a way to iterate from a certain point.
Upvotes: 2
Views: 269
Reputation: 1230
You can use a SortedSet, it's a Set that further provides a total ordering on its elements. The elements are ordered using their natural ordering or by a Comparator typically provided at sorted set creation time (doc here).
Upvotes: 0
Reputation: 421130
If you...
you can use TreeSet
.
Demo:
TreeSet<Integer> ints = new TreeSet<>(Arrays.asList(2,4,5,9,11));
System.out.println(ints.tailSet(4, false)); // [5, 9, 11]
System.out.println(ints.headSet(4, false)); // [2]
(If you want a Map
you can use TreeMap
with tailMap
and headMap
.)
Upvotes: 3