org.osgl.util.KVStore Maven / Gradle / Ivy
package org.osgl.util;
/*-
* #%L
* Java Tool
* %%
* Copyright (C) 2014 - 2017 OSGL (Open Source General Library)
* %%
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* #L%
*/
import java.util.HashMap;
import java.util.Map;
/**
* A simple implementation of {@link KV} using {@link HashMap}
*/
@SuppressWarnings("unused")
public class KVStore extends HashMap implements KV {
/**
* Create an empty {@code KVStore}
*/
public KVStore() {
}
/**
* Create a {@code KVStore} by coping another {@code KVStore}
* @param copy the KVStore in which all (K,V) pairs will be copied into the new KVStore instance
*/
public KVStore(KVStore copy) {
putAll(copy);
}
/**
* Create a {@code KVStore} with a (String, Object) map
* @param values the map in which all entries will be stored into the new KVStore instance
*/
public KVStore(Map values) {
putValues(values);
}
/**
* Put a simple data into the store with a key. The type of simple data
* should be allowed by {@link ValueObject}
* @param key the key
* @param val the value
* @return this store instance after the put operation finished
* @see ValueObject
*/
@Override
public KVStore putValue(String key, Object val) {
put(key, ValueObject.of(val));
return this;
}
/**
* Get {@link ValueObject#value() value object value} by key from the
* store.
* @param key the key
* @param the generic type of the return value
* @return the value stored in the value object associated with the key
* @see ValueObject#value()
*/
@Override
public T getValue(String key) {
ValueObject vo = get(key);
if (null == vo) {
return null;
}
return vo.value();
}
/**
* Put a map of (key, value) pair into the store. The value could be any type
* that supported by {@link ValueObject}
* @param kvMap a map of {key, value} pair
*/
@Override
public KVStore putValues(Map kvMap) {
for (String key : kvMap.keySet()) {
put(key, ValueObject.of(kvMap.get(key)));
}
return this;
}
/**
* Returns a `Map` contains (key, value) pairs that stored in this
* `KVStore`. The value in the pair should be the {@link ValueObject#value()}
* stored in the {@link ValueObject} in this `KVStore`
*
* @return the map of key and raw value stored in this store
*/
@Override
public Map toMap() {
Map map = C.newMap();
for (Map.Entry entry : entrySet()) {
map.put(entry.getKey(), entry.getValue().value());
}
return map;
}
}