If you can sort the items up by the value attribute, you can use LinkedListHashMap , as this preserves the order you specify. However, this seems a little fragile and not suitable if you need to add a few more elements to the map.
An alternative is to store values โโin a list sorted as needed, and use a binary search to retrieve items and search for insertion points for new items.
You can even wrap it all up and put it in the Map interface.
The Collections class provides binarySearch . Here is the diagram:
- Place the Value class on the list,
List<Value> values . - Introduce the
Comparable<Value> class, which compares values โโusing the attribute you want to sort. - 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 is not a real value - it is a value with attributes set to provide the key, but the rest is not unenalized. AValue is used only to store 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 in a map interface, for example. Extending AbstractMap, it will be serializable.
mdma
source share