If you can sort your items up front by the value attribute, then you can use a LinkedListHashMap
, since that preserves the order you specify. However, this seems a bit fragile, and is not suitable if you need to later add more items to the map.
The alternative is to store the values in a list, sorted as you need, and use binary search to retrieve items and find the insertion point for new items.
You can even wrap all this and put it behind a Map
interface.
The Collections class provides binarySearch. Here's an outline:
- Put your Value class in a list,
List<Value> values
.
- Implement a
Comparable<Value>
class that compares values using the attribute you want to sort them on.
- Use
Comparator<Value>
to sort the list.
- Now that the list is sorted, you can use
Collections.binarySearch(values, aValue, Comparator<Value>)
to find the index of the actual value. Note that aValue isn't a real value - it's a value with the attributes set to provide the key, but the rest of it is uninitalized. The aValue is only used to hold the sort key.
In code
List<Value> values = new ArrayList<Values>();
// .. add values
values.add(new Value(key, data1, data2, etc..));
Comparator<Value> compValue = new Comparator<Value>() {
public int compare(Value v1, Value v2) {
return v1.getKey()>v2.getKey();
}
}
Collections.sort(values, compValue);
// now we can search on key
int index = Collections.binarySearch(values, new Value(keyTofind), valueComp);
Value foundValue = null; // value with the key may not be in the list
if (index>=0)
foundValue = values.get(index);
// we can also update the list
Value newValue = new Value(key, data, data2, etc...);
int insert = Collections.binarySearch(values, newValue, valueComp);
// insert will be negative
values.add((-insert)-1, newValue);
EDIT: If you wrap this up in a Map interface, e.g. extending AbstractMap, it will be serializable.