net.sf.javagimmicks.collections8.transformer.MappedTransformerUtils Maven / Gradle / Ivy
Show all versions of gimmicks Show documentation
package net.sf.javagimmicks.collections8.transformer;
import java.util.Map;
import java.util.function.Function;
import net.sf.javagimmicks.collections.bidimap.BidiMap;
import net.sf.javagimmicks.transform8.BidiFunction;
/**
* Provides features to build {@link Function}s based on {@link Map}s and
* {@link BidiFunction}s based on {@link BidiMap}s.
*/
public class MappedTransformerUtils
{
private MappedTransformerUtils()
{}
/**
* Creates a new {@link Function} based on a given {@link Map} which
* transforms values by looking them up in the given {@link Map}.
*
* Attention: the resulting {@link Function} will throw an
* {@link IllegalArgumentException} if it should transform a value the has no
* corresponding key within the given {@link Map}.
*
* @param map
* the {@link Map} to wrap into a {@link Function}
* @param
* the "from" or source type
* @param
* the "to" or target type
* @return the resulting {@link Function}
*/
public static Function asFunction(final Map map)
{
return new MapFunction(map);
}
/**
* Creates a new {@link BidiFunction} based on a given {@link BidiMap} which
* transforms values by looking them up in the given {@link BidiMap}.
*
* Attention: the resulting {@link BidiFunction} will throw an
* {@link IllegalArgumentException} if it should transform a value the has no
* corresponding key (or value) within the given {@link BidiMap}.
*
* @param bidiMap
* the {@link BidiMap} to wrap into a {@link BidiFunction}
* @param
* the "from" or source type
* @param
* the "to" or target type
* @return the resulting {@link BidiFunction}
*/
public static BidiFunction asBidiFunction(final BidiMap bidiMap)
{
return new BidiMapBidiFunction(bidiMap);
}
protected static class MapFunction implements Function
{
protected final Map _baseMap;
protected MapFunction(final Map map)
{
_baseMap = map;
}
@Override
public T apply(final F source)
{
if (!_baseMap.containsKey(source))
{
throw new IllegalArgumentException("This MapTransformer doesn't contain the given source element '"
+ source + "'!");
}
return _baseMap.get(source);
}
}
protected static class BidiMapBidiFunction extends MapFunction implements BidiFunction
{
protected BidiMapBidiFunction(final BidiMap map)
{
super(map);
}
@Override
public F applyReverse(final T target)
{
if (!_baseMap.containsValue(target))
{
throw new IllegalArgumentException("This BidiMapTransformer doesn't contain the given target element '"
+ target + "'!");
}
return ((BidiMap) _baseMap).getKey(target);
}
}
}