UnitConverter.java

  1. package de.turnertech.ows.common;

  2. import java.util.HashMap;
  3. import java.util.Map;
  4. import java.util.Optional;

  5. public class UnitConverter {
  6.    
  7.     private UnitConverter() {}

  8.     private static final Map<Unit[], Double> scalarMap = new HashMap<>();

  9.     static {
  10.         scalarMap.put(new Unit[]{Unit.NAUTICAL_MILE, Unit.CENTIMETRE}, 185200.0);
  11.         scalarMap.put(new Unit[]{Unit.NAUTICAL_MILE, Unit.METRE}, 1852.0);
  12.         scalarMap.put(new Unit[]{Unit.NAUTICAL_MILE, Unit.KILOMETRE}, 1.852);
  13.         scalarMap.put(new Unit[]{Unit.KILOMETRE, Unit.METRE}, 1000.0);
  14.         scalarMap.put(new Unit[]{Unit.KILOMETRE, Unit.CENTIMETRE}, 100000.0);
  15.         scalarMap.put(new Unit[]{Unit.METRE, Unit.CENTIMETRE}, 100.0);
  16.         scalarMap.put(new Unit[]{Unit.INCH, Unit.CENTIMETRE}, 2.54);
  17.         scalarMap.put(new Unit[]{Unit.FOOT, Unit.METRE}, 0.3048);
  18.     }

  19.     public static Double putScalar(Unit from, Unit to, double scalar) {
  20.         if(scalar == 0.0) {
  21.             throw new ArithmeticException("Do not add a scalar value of 0 to UnitConverter. This can cause divide by 0 fails in the event the scalar is used as a divisor");
  22.         }
  23.         return scalarMap.put(new Unit[]{from, to}, scalar);
  24.     }


  25.     public static Optional<Double> convert(Unit from, Unit to, double value) {
  26.         if(from == to) {
  27.             return Optional.of(value);
  28.         }

  29.         Double scalar = scalarMap.getOrDefault(new Unit[]{from, to}, null);
  30.         if(scalar != null) {
  31.             return Optional.of(value * scalar);
  32.         }
  33.        
  34.         Double divisor = scalarMap.getOrDefault(new Unit[]{to, from}, null);
  35.         if(divisor != null) {
  36.             return Optional.of(value / divisor);
  37.         }

  38.         return Optional.empty();
  39.     }
  40. }