Java Properties dupe key detect using subclass

And now for the final word on this ‘problem’, the simplest approach is just to subclass the Properties class. The Properties class extends HashTable and uses it’s put(key,value) method. So we just override that method to do the duplicate key detection.

This was also addressed using Groovy scripting in this post, “Remove duplicate lines using Groovy”.

Source also available as a gist.

package com.octodecillion.util;

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;

			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);
		return results;

Nice tutorial on Anonymous classes: Anonymous Classes

One thought on “Java Properties dupe key detect using subclass”

Leave a Reply

Your email address will not be published. Required fields are marked *