How to create a (key, value1, value2) file in java similar to (key, value) property file
Can you please suggest how to create (key, value1, value2) file in java similar to (key, value) property file. Do any open source project uses such type of file.
You can use a delimiter:
props.put(key, value1 + DELIMITER + value2);
you can also use a key-suffix:
props.put(key + "1", value1);
props.put(key + "2", value2);
Commons Configuration has the PropertiesConfiguration class that supports multiple values for a single key.
See here for an example.
you can also use the apache commons collection package it has a handy MultiValue map implementation. See the Javadoc for more info
Thinking of multi-valued
property files. The Properties
class extends from Hashtable. You can create a new class that makes use of Hashtable<String, String[]>
Take the source code of java/utils/Properties.java and modify accordingly.
Here is how your property file should look like:
key1 = value
key2 = value_1
key2 = value_2
key3 = my_value_3
You could extends Map interface, something like :
public class Multimap<K, V> extends HashMap<K, V[]> {
@Override
public V[] put(K key, V...value) {
return super.put(key, value);
}
}
Then
Multimap<String,String> mapStr = new Multimap<String, String>();
mapStr.put("key1", "value1", "value2");
System.out.println("Strings: key1 = " + Arrays.toString( mapStr.get("key1") ) );
Multimap<String,Integer> mapInt = new Multimap<String, Integer>();
mapInt.put("key1", 1, 2);
System.out.println("Integers: key1 = " + Arrays.toString( mapInt.get("key1") ) );
Would yield
Strings: key1 = [value1, value2]
Integers: key1 = [1, 2]
You can also try something like this.
prop1 = one
prop2 =two
#prop12 is a multivalued property.values are the combination of prop1 and prop2
prop12= prop1,prop2
Assuming that the property file has entries like this.
public class MVProperties extends Properties{
public List<String> getMultiValuedProperty(String key){
List<String> values = null;
String[] references = getProperty(key,"").split(",");
if(references.length == 0){
return values;
}
values = new ArrayList<String>();
for(String ref:references){
values.add(getProperty(ref));
}
return values;
}
}
Use (key,value[]) instead
The simplest way to do it has already been suggested - if however you were looking for a way to modify a class that implements the Map interface to accept 2 values instead of just 1 then be careful. The Map interface has lots of methods that may behave in unexpected ways if you try this - it can be done its just a lot more work than it may be worth :)
精彩评论