me.landmesser.simplecsv.converter.EnumConverter Maven / Gradle / Ivy
Go to download
Show more of this group Show more artifacts with this name
Show all versions of simplecsv Show documentation
Show all versions of simplecsv Show documentation
Module that allows exporting Java beans into CSV format. Configuration
can be done via annotations. Under the hood, apache commons csv is used for writing
package me.landmesser.simplecsv.converter;
import me.landmesser.simplecsv.util.Pair;
import java.util.Arrays;
import java.util.EnumMap;
import java.util.Map;
import java.util.function.Function;
import java.util.stream.Collectors;
import java.util.stream.Stream;
public class EnumConverter> implements CSVConverter {
private final Map valueMapping;
public EnumConverter(Class type) {
valueMapping = new EnumMap<>(
Arrays.stream(type.getEnumConstants()).collect(
Collectors.toMap(Function.identity(), Enum::name)));
}
public EnumConverter(Class type, Map valueMapping) {
this(type);
if (valueMapping != null) {
this.valueMapping.putAll(valueMapping);
}
}
public EnumConverter(Class type, Stream> mapping) {
this(type, mapping.collect(Collectors.toMap(Pair::getFirst, Pair::getSecond)));
}
@Override
public String convert(T value) {
if (value == null) {
return null;
}
return valueMapping.get(value);
}
@Override
public T parse(String value) throws CSVConversionException {
if (value == null) {
return null;
}
return valueMapping.entrySet().stream().filter(e -> value.equals(e.getValue()))
.findFirst().map(Map.Entry::getKey).orElseThrow(CSVConversionException::new);
}
}