All Downloads are FREE. Search and download functionalities are using the official Maven repository.

me.landmesser.simplecsv.converter.EnumConverter Maven / Gradle / Ivy

Go to download

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

There is a newer version: 1.0
Show newest version
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);
  }
}




© 2015 - 2024 Weber Informatics LLC | Privacy Policy