Last active
November 22, 2015 18:48
Star
You must be signed in to star a gist
Example code to accompany blog post http://octodecillion.com/blog/java-properties-dupe-key-detect-using-subclass/
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package com.octodecillion.util; | |
import java.io.IOException; | |
import java.io.Reader; | |
import java.util.ArrayList; | |
import java.util.HashMap; | |
import java.util.List; | |
import java.util.Map; | |
import java.util.Properties; | |
/** | |
* Detect duplicate properties when loading Properties from stream. | |
* <p> | |
* | |
* @author jbetancourt | |
* @since Nov 18, 2015 | |
*/ | |
public class DuplicatePropertyDetectorWithSubClass { | |
/** | |
* Detect duplicate keys in Properties resource. | |
* <p> | |
* @see Properties#load(Reader) | |
* | |
* @param reader The reader is <b>NOT</b> closed. | |
* @return Map Map where map key is duplicated key and list is values of those keys | |
* @throws IOException reading the stream | |
* @throws Exception | |
*/ | |
public Map<String, List<String>> load(Reader reader) throws Exception { | |
if(reader==null){ throw new NullPointerException("reader cannot be null");} | |
final Map<String, List<String>> results = new HashMap<>(); | |
Properties props = new Properties(){ | |
private static final long serialVersionUID = 1L; | |
@Override | |
public synchronized Object put(Object key, Object value) { | |
if (this.containsKey(key)) { | |
List<String> list = new ArrayList<>(); | |
if (results.containsKey(key)) { | |
list = results.get(key); | |
} else { | |
results.put((String) key, list); | |
} | |
list.add((String) value); | |
} | |
return super.put(key, value); | |
} | |
}; | |
props.load(reader); | |
return results; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment