воскресенье, ноября 14, 2010

Load Java properties in natural order.

Some times you need iterate Java properties file in the same order as the properties are declared in .properties file. To avoid making logical copy of java.util.Properties class a simple hack could be used:

InputStream is = ...;

final Map map = new LinkedHashMap();

Properties p = new Properties() {
@Override
public Object put(Object key, Object value) {
map.put(key.toString(), value.toString());
return super.put(key, value);
}
};
p.load(is);


What the code do:
1. Constructs an instance of LinkedHashMap - map which hlds elements in putting order.
2. Overrided method of Properties class stores parsed items into the map as well as into itself. Note that put(Object, Object) method invoked after each parsed properties line. So our map will be filled sequently line-by-line and will hold the filling order.

After loading properties file, the Properties object is no longer needed - the LinkedHashMap will be used instead.

Thats all.
Enjoy.