@Override public MultiCurrencyAmountArray build() { return new MultiCurrencyAmountArray( size, values); }
/** * Obtains an instance from a map of amounts. * <p> * Each currency is associated with an array of amounts. * All the arrays must have the same number of elements. * <p> * If the map is empty the returned array will have a size of zero. To create an empty array * with a non-zero size use one of the other {@code of} methods. * * @param values map of currencies to values * @return an instance containing the values from the map */ public static MultiCurrencyAmountArray of(Map<Currency, DoubleArray> values) { values.values().stream().reduce((a1, a2) -> checkSize(a1, a2)); // All of the values must have the same size so use the size of the first int size = values.isEmpty() ? 0 : values.values().iterator().next().size(); return new MultiCurrencyAmountArray(size, values); }
/** * Obtains an instance using a function to create the entries. * <p> * The function is passed the index and returns the {@code MultiCurrencyAmount} for that index. * * @param size the number of elements, at least size one * @param valueFunction the function used to obtain each value * @return an instance initialized using the function * @throws IllegalArgumentException is size is zero or less */ public static MultiCurrencyAmountArray of(int size, IntFunction<MultiCurrencyAmount> valueFunction) { Map<Currency, double[]> map = new HashMap<>(); for (int i = 0; i < size; i++) { MultiCurrencyAmount mca = valueFunction.apply(i); for (CurrencyAmount ca : mca.getAmounts()) { double[] array = map.computeIfAbsent(ca.getCurrency(), c -> new double[size]); array[i] = ca.getAmount(); } } return new MultiCurrencyAmountArray(size, MapStream.of(map).mapValues(array -> DoubleArray.ofUnsafe(array)).toMap()); }
/** * Obtains an instance from the specified multi-currency amounts. * * @param amounts the amounts * @return an instance with the specified amounts */ public static MultiCurrencyAmountArray of(List<MultiCurrencyAmount> amounts) { int size = amounts.size(); HashMap<Currency, double[]> valueMap = new HashMap<>(); for (int i = 0; i < size; i++) { MultiCurrencyAmount multiCurrencyAmount = amounts.get(i); for (CurrencyAmount currencyAmount : multiCurrencyAmount.getAmounts()) { double[] currencyValues = valueMap.computeIfAbsent(currencyAmount.getCurrency(), ccy -> new double[size]); currencyValues[i] = currencyAmount.getAmount(); } } Map<Currency, DoubleArray> doubleArrayMap = MapStream.of(valueMap).mapValues(v -> DoubleArray.ofUnsafe(v)).toMap(); return new MultiCurrencyAmountArray(size, doubleArrayMap); }