/** * Obtains an instance from the specified currency and array of values. * * @param currency the currency of the values * @param values the values * @return an instance with the specified currency and values */ public static CurrencyAmountArray of(Currency currency, DoubleArray values) { return new CurrencyAmountArray(currency, values); }
@Override public CurrencyAmountArray build() { return new CurrencyAmountArray( currency, values); }
/** * Obtains an instance from the specified list of amounts. * <p> * All amounts must have the same currency. * * @param amounts the amounts, at least size one * @return an instance with the specified amounts * @throws IllegalArgumentException if multiple currencies are found */ public static CurrencyAmountArray of(List<CurrencyAmount> amounts) { Currency currency = amounts.stream() .map(ca -> ca.getCurrency()) .distinct() .reduce(ensureOnlyOne()) .get(); double[] values = amounts.stream() .mapToDouble(ca -> ca.getAmount()) .toArray(); return new CurrencyAmountArray(currency, DoubleArray.ofUnsafe(values)); }
@Override public CurrencyAmountArray convertedTo(Currency resultCurrency, FxRateProvider fxRateProvider) { if (currency.equals(resultCurrency)) { return this; } double fxRate = fxRateProvider.fxRate(currency, resultCurrency); DoubleArray convertedValues = values.multipliedBy(fxRate); return new CurrencyAmountArray(resultCurrency, convertedValues); }
/** * Obtains an instance using a function to create the entries. * <p> * The function is passed the index and returns the {@code CurrencyAmount} for that index. * <p> * In some cases it may be possible to specify the currency with a function providing a {@code double}. * To do this, use {@link DoubleArray#of(int, java.util.function.IntToDoubleFunction)} and * then call {@link #of(Currency, DoubleArray)}. * * @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 CurrencyAmountArray of(int size, IntFunction<CurrencyAmount> valueFunction) { ArgChecker.notNegativeOrZero(size, "size"); double[] array = new double[size]; CurrencyAmount ca0 = valueFunction.apply(0); Currency currency = ca0.getCurrency(); array[0] = ca0.getAmount(); for (int i = 1; i < size; i++) { CurrencyAmount ca = valueFunction.apply(i); if (!ca.getCurrency().equals(currency)) { throw new IllegalArgumentException(Messages.format("Currencies differ: {} and {}", currency, ca.getCurrency())); } array[i] = ca.getAmount(); } return new CurrencyAmountArray(currency, DoubleArray.ofUnsafe(array)); }