map = new HashMap<>(this.exponents);
for (final T key : this.exponents.keySet()) {
map.put(key, this.getExponent(key) * exponent);
}
return new ObjectProduct<>(map);
}
/**
* Converts this product to a string using the objects'
* {@link Object#toString()} method. If objects have a long toString
* representation, it is recommended to use {@link #toString(Function)}
* instead to shorten the returned string.
*
*
* {@inheritDoc}
*/
@Override
public String toString() {
return this
.toString(o -> o instanceof Nameable ? ((Nameable) o).getShortName()
: o.toString());
}
/**
* Converts this product to a string. The objects that make up this product
* are represented by {@code objectToString}
*
* @param objectToString function to convert objects to strings
* @return string representation of product
* @since 2019-10-16
*/
public String toString(final Function objectToString) {
final List positiveStringComponents = new ArrayList<>();
final List negativeStringComponents = new ArrayList<>();
// for each base object that makes up this object, add it and its exponent
for (final T object : this.getBaseSet()) {
final int exponent = this.exponents.get(object);
if (exponent > 1) {
positiveStringComponents.add(String.format("%s^%d",
objectToString.apply(object), exponent));
} else if (exponent == 1) {
positiveStringComponents.add(objectToString.apply(object));
} else if (exponent < 0) {
negativeStringComponents.add(String.format("%s^%d",
objectToString.apply(object), -exponent));
}
}
final String positiveString = positiveStringComponents.isEmpty() ? "1"
: String.join(" * ", positiveStringComponents);
final String negativeString = negativeStringComponents.isEmpty() ? ""
: " / " + String.join(" * ", negativeStringComponents);
return positiveString + negativeString;
}
/**
* @return named version of this {@code ObjectProduct}, using data from
* {@code nameSymbol}
* @since 2021-12-15
*/
public ObjectProduct withName(NameSymbol nameSymbol) {
return new ObjectProduct<>(this.exponents, nameSymbol);
}
}