使用对象和接口从 Map 的对象获取键

Getting key from object for Map using object and interface

我有一个 Table class 实现了某种类型对象的 ForwardingMultimap。我想知道创建一个从对象中提取密钥的接口是否过度,这样调用者在调用 "values" 时处理 "Entry" 对象就不会很烦人了。或者让调用者自己放置对象和键会更好吗?如果没问题,创建一个单独的 class 来处理下面的每个键会更好,还是调用者应该自己实现它?

public class CustomObject {
    public String propertyOne;
    public int propertyTwo;

}

public interface ITableAggKey {
    Object getKey(CustomObject customObj);
}

public class Table extends ForwardingMultimap<Object, CustomObject> {
    Multimap m_map;
    public Table(ITableAggKey aggKey){
        m_map = HashMultimap.create();
        m_aggKey = aggKey;
    }
    public boolean put(CustomObject obj) {
        m_map.put(m_aggKey.getKey(obj), obj);
    }
}

public class CustomObjectAggKeys {
    public static final aggKeyOne = new ITableAggKey(){
        @Overide
        public Object getKey(CustomObject obj){
            return obj.propertyOne;
        }
    };

    public static final aggKeyOne = new ITableAggKey(){
        @Overide
        public Object getKey(CustomObject obj){
            return obj.propertyTwo;
        }
    };
}
public class Table<K, T> extends ForwardingMultimap<K, T> {
    Multimap<K, T> m_map;
    Function<T, K> m_aggKey;
    public Table(Function<T, K> aggKey){
        m_map = HashMultimap.create();
        m_aggKey = aggKey;
    }
    public boolean put(T obj) {
        m_map.put(m_aggKey.apply(obj), obj);
    }
}

public static void main(String[] args) {
    Table<String, CustomObject> IndexOne = new Table<>(x -> x.propertyOne);
    Table<Integer, CustomObject> IndexTwo = new Table<>(x -> x.propertyTwo);
}

如果不能使用Java8。添加函数接口。

public interface Function<T, K> {
    K apply(T arg);
}

    Table<String, CustomObject> indexOne = new Table<>(new Function<CustomObject, String>() {
        @Override public String apply(CustomObject obj) {
            return obj.propertyOne;
        }
    });