summaryrefslogtreecommitdiff
path: root/src/main/java/sevenUnits/unit/UnitDatabase.java
diff options
context:
space:
mode:
Diffstat (limited to 'src/main/java/sevenUnits/unit/UnitDatabase.java')
-rw-r--r--src/main/java/sevenUnits/unit/UnitDatabase.java496
1 files changed, 228 insertions, 268 deletions
diff --git a/src/main/java/sevenUnits/unit/UnitDatabase.java b/src/main/java/sevenUnits/unit/UnitDatabase.java
index a85ec5f..05e9cc9 100644
--- a/src/main/java/sevenUnits/unit/UnitDatabase.java
+++ b/src/main/java/sevenUnits/unit/UnitDatabase.java
@@ -40,7 +40,6 @@ import java.util.Set;
import java.util.function.BiFunction;
import java.util.function.Function;
import java.util.function.Predicate;
-import java.util.regex.Matcher;
import java.util.regex.Pattern;
import sevenUnits.utils.ConditionalExistenceCollections;
@@ -51,7 +50,7 @@ import sevenUnits.utils.UncertainDouble;
/**
* A database of units, prefixes and dimensions, and their names.
- *
+ *
* @author Adrien Hopkins
* @since 2019-01-07
* @since v0.1.0
@@ -88,7 +87,7 @@ public final class UnitDatabase {
* Because of ambiguities between prefixes (i.e. kilokilo = mega),
* {@link #containsValue} and {@link #values()} currently ignore prefixes.
* </p>
- *
+ *
* @author Adrien Hopkins
* @since 2019-04-13
* @since v0.2.0
@@ -96,7 +95,7 @@ public final class UnitDatabase {
private static final class PrefixedUnitMap implements Map<String, Unit> {
/**
* The class used for entry sets.
- *
+ *
* <p>
* If the map that created this set is infinite in size (has at least one
* unit and at least one prefix), this set is infinite as well. If this
@@ -104,7 +103,7 @@ public final class UnitDatabase {
* {@code IllegalStateException} instead of creating an infinite-sized
* array.
* </p>
- *
+ *
* @author Adrien Hopkins
* @since 2019-04-13
* @since v0.2.0
@@ -113,7 +112,7 @@ public final class UnitDatabase {
extends AbstractSet<Map.Entry<String, Unit>> {
/**
* The entry for this set.
- *
+ *
* @author Adrien Hopkins
* @since 2019-04-14
* @since v0.2.0
@@ -125,7 +124,7 @@ public final class UnitDatabase {
/**
* Creates the {@code PrefixedUnitEntry}.
- *
+ *
* @param key key
* @param value value
* @since 2019-04-14
@@ -181,7 +180,7 @@ public final class UnitDatabase {
* string is the string representation of the key, then the equals
* ({@code =}) character, then the string representation of the
* value.
- *
+ *
* @since 2019-05-03
* @since v0.3.0
*/
@@ -194,7 +193,7 @@ public final class UnitDatabase {
/**
* An iterator that iterates over the units of a
* {@code PrefixedUnitNameSet}.
- *
+ *
* @author Adrien Hopkins
* @since 2019-04-14
* @since v0.2.0
@@ -214,9 +213,9 @@ public final class UnitDatabase {
/**
* Creates the
* {@code UnitsDatabase.PrefixedUnitMap.PrefixedUnitNameSet.PrefixedUnitNameIterator}.
- *
+ *
* @param map map to base iterator on
- *
+ *
* @since 2019-04-14
* @since v0.2.0
*/
@@ -232,7 +231,7 @@ public final class UnitDatabase {
* @since v0.2.0
*/
private String getCurrentUnitName() {
- final StringBuilder unitName = new StringBuilder();
+ final var unitName = new StringBuilder();
for (final int i : this.prefixCoordinates) {
unitName.append(this.prefixNames.get(i));
}
@@ -245,18 +244,15 @@ public final class UnitDatabase {
public boolean hasNext() {
if (this.unitNames.isEmpty())
return false;
- else {
- if (this.prefixNames.isEmpty())
- return this.prefixCoordinates.isEmpty()
- && this.unitNamePosition < this.unitNames.size();
- else
- return true;
- }
+ if (this.prefixNames.isEmpty())
+ return this.prefixCoordinates.isEmpty()
+ && this.unitNamePosition < this.unitNames.size();
+ return true;
}
/**
* Changes this iterator's position to the next available one.
- *
+ *
* @since 2019-04-14
* @since v0.2.0
*/
@@ -272,7 +268,7 @@ public final class UnitDatabase {
this.prefixCoordinates.add(0, 0);
} else {
// get the prefix coordinate to increment, then increment
- int i = this.prefixCoordinates.size() - 1;
+ var i = this.prefixCoordinates.size() - 1;
this.prefixCoordinates.set(i,
this.prefixCoordinates.get(i) + 1);
@@ -298,7 +294,7 @@ public final class UnitDatabase {
@Override
public Entry<String, Unit> next() {
// get next element
- final Entry<String, Unit> nextEntry = this.peek();
+ final var nextEntry = this.peek();
// iterate to next position
this.incrementPosition();
@@ -327,7 +323,7 @@ public final class UnitDatabase {
}
}
- final String nextName = this.getCurrentUnitName();
+ final var nextName = this.getCurrentUnitName();
return new PrefixedUnitEntry(nextName, this.map.get(nextName));
}
@@ -335,7 +331,7 @@ public final class UnitDatabase {
/**
* Returns a string representation of the object. The exact details
* of the representation are unspecified and subject to change.
- *
+ *
* @since 2019-05-03
* @since v0.3.0
*/
@@ -352,7 +348,7 @@ public final class UnitDatabase {
/**
* Creates the {@code PrefixedUnitNameSet}.
- *
+ *
* @param map map that created this set
* @since 2019-04-13
* @since v0.2.0
@@ -389,7 +385,7 @@ public final class UnitDatabase {
// This is OK because I'm in a try-catch block, catching the
// exact exception that would be thrown.
@SuppressWarnings("unchecked")
- final Entry<String, Unit> tempEntry = (Entry<String, Unit>) o;
+ final var tempEntry = (Entry<String, Unit>) o;
entry = tempEntry;
} catch (final ClassCastException e) {
throw new IllegalArgumentException(
@@ -447,55 +443,45 @@ public final class UnitDatabase {
public int size() {
if (this.map.units.isEmpty())
return 0;
- else {
- if (this.map.prefixes.isEmpty())
- return this.map.units.size();
- else
- // infinite set
- return Integer.MAX_VALUE;
- }
+ if (this.map.prefixes.isEmpty())
+ return this.map.units.size();
+ // infinite set
+ return Integer.MAX_VALUE;
}
- /**
- * @throws IllegalStateException if the set is infinite in size
- */
+ /** @throws IllegalStateException if the set is infinite in size */
@Override
public Object[] toArray() {
if (this.map.units.isEmpty() || this.map.prefixes.isEmpty())
return super.toArray();
- else
- // infinite set
- throw new IllegalStateException(
- "Cannot make an infinite set into an array.");
+ // infinite set
+ throw new IllegalStateException(
+ "Cannot make an infinite set into an array.");
}
- /**
- * @throws IllegalStateException if the set is infinite in size
- */
+ /** @throws IllegalStateException if the set is infinite in size */
@Override
public <T> T[] toArray(final T[] a) {
if (this.map.units.isEmpty() || this.map.prefixes.isEmpty())
return super.toArray(a);
- else
- // infinite set
- throw new IllegalStateException(
- "Cannot make an infinite set into an array.");
+ // infinite set
+ throw new IllegalStateException(
+ "Cannot make an infinite set into an array.");
}
@Override
public String toString() {
if (this.map.units.isEmpty() || this.map.prefixes.isEmpty())
return super.toString();
- else
- return String.format(
- "Infinite set of name-unit entries created from units %s and prefixes %s",
- this.map.units, this.map.prefixes);
+ return String.format(
+ "Infinite set of name-unit entries created from units %s and prefixes %s",
+ this.map.units, this.map.prefixes);
}
}
/**
* The class used for unit name sets.
- *
+ *
* <p>
* If the map that created this set is infinite in size (has at least one
* unit and at least one prefix), this set is infinite as well. If this
@@ -503,7 +489,7 @@ public final class UnitDatabase {
* {@code IllegalStateException} instead of creating an infinite-sized
* array.
* </p>
- *
+ *
* @author Adrien Hopkins
* @since 2019-04-13
* @since v0.2.0
@@ -513,7 +499,7 @@ public final class UnitDatabase {
/**
* An iterator that iterates over the units of a
* {@code PrefixedUnitNameSet}.
- *
+ *
* @author Adrien Hopkins
* @since 2019-04-14
* @since v0.2.0
@@ -533,9 +519,9 @@ public final class UnitDatabase {
/**
* Creates the
* {@code UnitsDatabase.PrefixedUnitMap.PrefixedUnitNameSet.PrefixedUnitNameIterator}.
- *
+ *
* @param map map to base itorator on
- *
+ *
* @since 2019-04-14
* @since v0.2.0
*/
@@ -551,7 +537,7 @@ public final class UnitDatabase {
* @since v0.2.0
*/
private String getCurrentUnitName() {
- final StringBuilder unitName = new StringBuilder();
+ final var unitName = new StringBuilder();
for (final int i : this.prefixCoordinates) {
unitName.append(this.prefixNames.get(i));
}
@@ -564,18 +550,15 @@ public final class UnitDatabase {
public boolean hasNext() {
if (this.unitNames.isEmpty())
return false;
- else {
- if (this.prefixNames.isEmpty())
- return this.prefixCoordinates.isEmpty()
- && this.unitNamePosition < this.unitNames.size();
- else
- return true;
- }
+ if (this.prefixNames.isEmpty())
+ return this.prefixCoordinates.isEmpty()
+ && this.unitNamePosition < this.unitNames.size();
+ return true;
}
/**
* Changes this iterator's position to the next available one.
- *
+ *
* @since 2019-04-14
* @since v0.2.0
*/
@@ -591,7 +574,7 @@ public final class UnitDatabase {
this.prefixCoordinates.add(0, 0);
} else {
// get the prefix coordinate to increment, then increment
- int i = this.prefixCoordinates.size() - 1;
+ var i = this.prefixCoordinates.size() - 1;
this.prefixCoordinates.set(i,
this.prefixCoordinates.get(i) + 1);
@@ -616,7 +599,7 @@ public final class UnitDatabase {
@Override
public String next() {
- final String nextName = this.peek();
+ final var nextName = this.peek();
this.incrementPosition();
@@ -649,7 +632,7 @@ public final class UnitDatabase {
/**
* Returns a string representation of the object. The exact details
* of the representation are unspecified and subject to change.
- *
+ *
* @since 2019-05-03
* @since v0.3.0
*/
@@ -666,7 +649,7 @@ public final class UnitDatabase {
/**
* Creates the {@code PrefixedUnitNameSet}.
- *
+ *
* @param map map that created this set
* @since 2019-04-13
* @since v0.2.0
@@ -744,56 +727,46 @@ public final class UnitDatabase {
public int size() {
if (this.map.units.isEmpty())
return 0;
- else {
- if (this.map.prefixes.isEmpty())
- return this.map.units.size();
- else
- // infinite set
- return Integer.MAX_VALUE;
- }
+ if (this.map.prefixes.isEmpty())
+ return this.map.units.size();
+ // infinite set
+ return Integer.MAX_VALUE;
}
- /**
- * @throws IllegalStateException if the set is infinite in size
- */
+ /** @throws IllegalStateException if the set is infinite in size */
@Override
public Object[] toArray() {
if (this.map.units.isEmpty() || this.map.prefixes.isEmpty())
return super.toArray();
- else
- // infinite set
- throw new IllegalStateException(
- "Cannot make an infinite set into an array.");
+ // infinite set
+ throw new IllegalStateException(
+ "Cannot make an infinite set into an array.");
}
- /**
- * @throws IllegalStateException if the set is infinite in size
- */
+ /** @throws IllegalStateException if the set is infinite in size */
@Override
public <T> T[] toArray(final T[] a) {
if (this.map.units.isEmpty() || this.map.prefixes.isEmpty())
return super.toArray(a);
- else
- // infinite set
- throw new IllegalStateException(
- "Cannot make an infinite set into an array.");
+ // infinite set
+ throw new IllegalStateException(
+ "Cannot make an infinite set into an array.");
}
@Override
public String toString() {
if (this.map.units.isEmpty() || this.map.prefixes.isEmpty())
return super.toString();
- else
- return String.format(
- "Infinite set of name-unit entries created from units %s and prefixes %s",
- this.map.units, this.map.prefixes);
+ return String.format(
+ "Infinite set of name-unit entries created from units %s and prefixes %s",
+ this.map.units, this.map.prefixes);
}
}
/**
* The units stored in this collection, without prefixes.
- *
+ *
* @since 2019-04-13
* @since v0.2.0
*/
@@ -801,7 +774,7 @@ public final class UnitDatabase {
/**
* The available prefixes for use.
- *
+ *
* @since 2019-04-13
* @since v0.2.0
*/
@@ -814,7 +787,7 @@ public final class UnitDatabase {
/**
* Creates the {@code PrefixedUnitMap}.
- *
+ *
* @param units map mapping unit names to units
* @param prefixes map mapping prefix names to prefixes
* @since 2019-04-13
@@ -865,11 +838,11 @@ public final class UnitDatabase {
if (!(key instanceof String))
throw new IllegalArgumentException(
"Attempted to test for a unit using a non-string name.");
- final String unitName = (String) key;
+ final var unitName = (String) key;
// Then, look for the longest prefix that is attached to a valid unit
String longestPrefix = null;
- int longestLength = 0;
+ var longestLength = 0;
for (final String prefixName : this.prefixes.keySet()) {
// a prefix name is valid if:
@@ -881,7 +854,7 @@ public final class UnitDatabase {
// linear units can have prefixes)
if (unitName.startsWith(prefixName)
&& prefixName.length() > longestLength) {
- final String rest = unitName.substring(prefixName.length());
+ final var rest = unitName.substring(prefixName.length());
if (this.containsKey(rest)
&& this.get(rest) instanceof LinearUnit) {
longestPrefix = prefixName;
@@ -895,7 +868,7 @@ public final class UnitDatabase {
/**
* {@inheritDoc}
- *
+ *
* <p>
* Because of ambiguities between prefixes (i.e. kilokilo = mega), this
* method only tests for prefixless units.
@@ -924,11 +897,11 @@ public final class UnitDatabase {
if (!(key instanceof String))
throw new IllegalArgumentException(
"Attempted to obtain a unit using a non-string name.");
- final String unitName = (String) key;
+ final var unitName = (String) key;
// Then, look for the longest prefix that is attached to a valid unit
String longestPrefix = null;
- int longestLength = 0;
+ var longestLength = 0;
for (final String prefixName : this.prefixes.keySet()) {
// a prefix name is valid if:
@@ -940,7 +913,7 @@ public final class UnitDatabase {
// linear units can have prefixes)
if (unitName.startsWith(prefixName)
&& prefixName.length() > longestLength) {
- final String rest = unitName.substring(prefixName.length());
+ final var rest = unitName.substring(prefixName.length());
if (this.containsKey(rest)
&& this.get(rest) instanceof LinearUnit) {
longestPrefix = prefixName;
@@ -952,16 +925,14 @@ public final class UnitDatabase {
// if none found, returns null
if (longestPrefix == null)
return null;
- else {
- // get necessary data
- final String rest = unitName.substring(longestLength);
- // this cast will not fail because I verified that it would work
- // before selecting this prefix
- final LinearUnit unit = (LinearUnit) this.get(rest);
- final UnitPrefix prefix = this.prefixes.get(longestPrefix);
-
- return unit.withPrefix(prefix);
- }
+ // get necessary data
+ final var rest = unitName.substring(longestLength);
+ // this cast will not fail because I verified that it would work
+ // before selecting this prefix
+ final var unit = (LinearUnit) this.get(rest);
+ final var prefix = this.prefixes.get(longestPrefix);
+
+ return unit.withPrefix(prefix);
}
@Override
@@ -1038,28 +1009,24 @@ public final class UnitDatabase {
public int size() {
if (this.units.isEmpty())
return 0;
- else {
- if (this.prefixes.isEmpty())
- return this.units.size();
- else
- // infinite set
- return Integer.MAX_VALUE;
- }
+ if (this.prefixes.isEmpty())
+ return this.units.size();
+ // infinite set
+ return Integer.MAX_VALUE;
}
@Override
public String toString() {
if (this.units.isEmpty() || this.prefixes.isEmpty())
return new HashMap<>(this).toString();
- else
- return String.format(
- "Infinite map of name-unit entries created from units %s and prefixes %s",
- this.units, this.prefixes);
+ return String.format(
+ "Infinite map of name-unit entries created from units %s and prefixes %s",
+ this.units, this.prefixes);
}
/**
* {@inheritDoc}
- *
+ *
* <p>
* Because of ambiguities between prefixes (i.e. kilokilo = mega), this
* method ignores prefixes.
@@ -1090,60 +1057,60 @@ public final class UnitDatabase {
/**
* The exponent operator
- *
+ *
* @param base base of exponentiation
* @param exponentUnit exponent
* @return result
* @since 2019-04-10
* @since v0.2.0
*/
- private static final LinearUnit exponentiateUnits(final LinearUnit base,
+ private static LinearUnit exponentiateUnits(final LinearUnit base,
final LinearUnit exponentUnit) {
if (!exponentUnit.getBase().equals(Metric.ONE.getBase()))
throw new IllegalArgumentException(String.format(
"Tried to exponentiate %s^%s, but exponents must be dimensionless numbers.",
base, exponentUnit));
- final double exponent = exponentUnit.getConversionFactor();
+ final var exponent = exponentUnit.getConversionFactor();
return base.toExponentRounded(exponent);
}
/**
* The exponent operator
- *
+ *
* @param base base of exponentiation
* @param exponentUnit exponent
* @return result
* @since 2020-08-04
* @since v0.3.0
*/
- private static final LinearUnitValue exponentiateUnitValues(
+ private static LinearUnitValue exponentiateUnitValues(
final LinearUnitValue base, final LinearUnitValue exponentValue) {
if (!exponentValue.canConvertTo(Metric.ONE))
throw new IllegalArgumentException(String.format(
"Tried to exponentiate %s^%s, but exponents must be dimensionless numbers.",
base, exponentValue));
- final double exponent = exponentValue.getValueExact();
+ final var exponent = exponentValue.getValueExact();
return base.toExponentRounded(exponent);
}
/**
* Formats an expression so it can be parsed by the expression parser.
- *
+ *
* Specifically, puts spaces around all operators so they can be parsed as
* words.
- *
+ *
* @param expression expression to format
* @return formatted expression
* @since 2025-06-07
* @since v1.0.0
*/
- static final String formatExpression(String expression) {
- String modifiedExpression = expression;
+ static String formatExpression(String expression) {
+ var modifiedExpression = expression;
for (final String operator : Arrays.asList("\\*", "/", "\\|", "\\^")) {
- modifiedExpression = modifiedExpression.replaceAll(
- operator, " " + operator + " ");
+ modifiedExpression = modifiedExpression.replaceAll(operator,
+ " " + operator + " ");
}
modifiedExpression = modifiedExpression.replaceAll("\\s+", " ");
@@ -1158,8 +1125,8 @@ public final class UnitDatabase {
static <T> boolean isRemovableDuplicate(Map<String, T> map,
Entry<String, T> entry) {
for (final Entry<String, T> e : map.entrySet()) {
- final String name = e.getKey();
- final T value = e.getValue();
+ final var name = e.getKey();
+ final var value = e.getValue();
if (lengthFirstComparator.compare(entry.getKey(), name) < 0
&& Objects.equals(map.get(entry.getKey()), value))
return true;
@@ -1169,7 +1136,7 @@ public final class UnitDatabase {
/**
* The units in this system, excluding prefixes.
- *
+ *
* @since 2019-01-07
* @since v0.1.0
*/
@@ -1177,7 +1144,7 @@ public final class UnitDatabase {
/**
* The unit prefixes in this system.
- *
+ *
* @since 2019-01-14
* @since v0.1.0
*/
@@ -1185,7 +1152,7 @@ public final class UnitDatabase {
/**
* The dimensions in this system.
- *
+ *
* @since 2019-03-14
* @since v0.2.0
*/
@@ -1193,7 +1160,7 @@ public final class UnitDatabase {
/**
* A map mapping strings to units (including prefixes)
- *
+ *
* @since 2019-04-13
* @since v0.2.0
*/
@@ -1201,7 +1168,7 @@ public final class UnitDatabase {
/**
* A map mapping strings to unit sets
- *
+ *
* @since 2024-08-16
* @since v1.0.0
*/
@@ -1221,74 +1188,74 @@ public final class UnitDatabase {
/**
* A parser that can parse unit expressions.
- *
+ *
* @since 2019-03-22
* @since v0.2.0
*/
private final ExpressionParser<LinearUnit> unitExpressionParser = new ExpressionParser.Builder<>(
- this::getLinearUnit).addBinaryOperator("+", (o1, o2) -> o1.plus(o2), 0)
- .addBinaryOperator("-", (o1, o2) -> o1.minus(o2), 0)
- .addBinaryOperator("*", (o1, o2) -> o1.times(o2), 1)
- .addBinaryOperator("space_times", (o1, o2) -> o1.times(o2), 2)
+ this::getLinearUnit).addBinaryOperator("+", LinearUnit::plus, 0)
+ .addBinaryOperator("-", LinearUnit::minus, 0)
+ .addBinaryOperator("*", LinearUnit::times, 1)
+ .addBinaryOperator("space_times", LinearUnit::times, 2)
.addSpaceFunction("space_times")
- .addBinaryOperator("/", (o1, o2) -> o1.dividedBy(o2), 1)
- .addBinaryOperator("|", (o1, o2) -> o1.dividedBy(o2), 4)
+ .addBinaryOperator("/", LinearUnit::dividedBy, 1)
+ .addBinaryOperator("|", LinearUnit::dividedBy, 4)
.addBinaryOperator("^", UnitDatabase::exponentiateUnits, 3).build();
/**
* A parser that can parse unit value expressions.
- *
+ *
* @since 2020-08-04
* @since v0.3.0
*/
private final ExpressionParser<LinearUnitValue> unitValueExpressionParser = new ExpressionParser.Builder<>(
this::getLinearUnitValue)
- .addBinaryOperator("+", (o1, o2) -> o1.plus(o2), 0)
- .addBinaryOperator("-", (o1, o2) -> o1.minus(o2), 0)
- .addBinaryOperator("*", (o1, o2) -> o1.times(o2), 1)
- .addBinaryOperator("space_times", (o1, o2) -> o1.times(o2), 2)
+ .addBinaryOperator("+", LinearUnitValue::plus, 0)
+ .addBinaryOperator("-", LinearUnitValue::minus, 0)
+ .addBinaryOperator("*", LinearUnitValue::times, 1)
+ .addBinaryOperator("space_times", LinearUnitValue::times, 2)
.addSpaceFunction("space_times")
- .addBinaryOperator("/", (o1, o2) -> o1.dividedBy(o2), 1)
- .addBinaryOperator("|", (o1, o2) -> o1.dividedBy(o2), 4)
+ .addBinaryOperator("/", LinearUnitValue::dividedBy, 1)
+ .addBinaryOperator("|", LinearUnitValue::dividedBy, 4)
.addBinaryOperator("^", UnitDatabase::exponentiateUnitValues, 3)
.build();
/**
* A parser that can parse unit prefix expressions
- *
+ *
* @since 2019-04-13
* @since v0.2.0
*/
private final ExpressionParser<UnitPrefix> prefixExpressionParser = new ExpressionParser.Builder<>(
- this::getPrefix).addBinaryOperator("+", (o1, o2) -> o1.plus(o2), 0)
- .addBinaryOperator("-", (o1, o2) -> o1.minus(o2), 0)
- .addBinaryOperator("*", (o1, o2) -> o1.times(o2), 1)
+ this::getPrefix).addBinaryOperator("+", UnitPrefix::plus, 0)
+ .addBinaryOperator("-", UnitPrefix::minus, 0)
+ .addBinaryOperator("*", UnitPrefix::times, 1)
.addSpaceFunction("*")
- .addBinaryOperator("/", (o1, o2) -> o1.dividedBy(o2), 1)
- .addBinaryOperator("|", (o1, o2) -> o1.dividedBy(o2), 3)
+ .addBinaryOperator("/", UnitPrefix::dividedBy, 1)
+ .addBinaryOperator("|", UnitPrefix::dividedBy, 3)
.addBinaryOperator("^", (o1, o2) -> o1.toExponent(o2.getMultiplier()),
2)
.build();
/**
* A parser that can parse unit dimension expressions.
- *
+ *
* @since 2019-04-13
* @since v0.2.0
*/
private final ExpressionParser<ObjectProduct<BaseDimension>> unitDimensionParser = new ExpressionParser.Builder<>(
- this::getDimension).addBinaryOperator("*", (o1, o2) -> o1.times(o2), 0)
+ this::getDimension).addBinaryOperator("*", ObjectProduct::times, 0)
.addSpaceFunction("*")
- .addBinaryOperator("/", (o1, o2) -> o1.dividedBy(o2), 0)
- .addBinaryOperator("|", (o1, o2) -> o1.dividedBy(o2), 2)
+ .addBinaryOperator("/", ObjectProduct::dividedBy, 0)
+ .addBinaryOperator("|", ObjectProduct::dividedBy, 2)
.addNumericOperator("^", (o1, o2) -> {
- final int exponent = (int) Math.round(o2.value());
+ final var exponent = (int) Math.round(o2.value());
return o1.toExponent(exponent);
}, 1).build();
/**
* Creates the {@code UnitsDatabase}.
- *
+ *
* @since 2019-01-10
* @since v0.1.0
*/
@@ -1298,7 +1265,7 @@ public final class UnitDatabase {
/**
* Creates the {@code UnitsDatabase}
- *
+ *
* @param prefixRepetitionRule the rule that determines when prefix
* repetition is allowed
* @since 2020-08-26
@@ -1318,7 +1285,7 @@ public final class UnitDatabase {
/**
* Adds a unit dimension to the database.
- *
+ *
* @param name dimension's name
* @param dimension dimension to add
* @throws NullPointerException if name or dimension is null
@@ -1329,14 +1296,14 @@ public final class UnitDatabase {
final ObjectProduct<BaseDimension> dimension) {
Objects.requireNonNull(name, "name may not be null");
Objects.requireNonNull(dimension, "dimension may not be null");
- final ObjectProduct<BaseDimension> namedDimension = dimension
+ final var namedDimension = dimension
.withName(dimension.getNameSymbol().withExtraName(name));
this.dimensions.put(name, namedDimension);
}
/**
* Adds to the list from a line in a unit dimension file.
- *
+ *
* @param line line to look at
* @param lineCounter number of line, for error messages
* @since 2019-04-10
@@ -1354,13 +1321,13 @@ public final class UnitDatabase {
}
// divide line into name and expression
- final Matcher lineMatcher = NAME_EXPRESSION.matcher(line);
+ final var lineMatcher = NAME_EXPRESSION.matcher(line);
if (!lineMatcher.matches())
throw new IllegalArgumentException(String.format(
"Error at line %d: Lines of a dimension file must consist of a dimension name, then spaces or tabs, then a dimension expression.",
lineCounter));
- final String name = lineMatcher.group(1);
- final String expression = lineMatcher.group(2);
+ final var name = lineMatcher.group(1);
+ final var expression = lineMatcher.group(2);
// if (name.endsWith(" ")) {
// System.err.printf("Warning - line %d's dimension name ends in a space",
@@ -1380,7 +1347,7 @@ public final class UnitDatabase {
/**
* Adds a unit prefix to the database.
- *
+ *
* @param name prefix's name
* @param prefix prefix to add
* @throws NullPointerException if name or prefix is null
@@ -1397,7 +1364,7 @@ public final class UnitDatabase {
/**
* Adds a unit to the database.
- *
+ *
* @param name unit's name
* @param unit unit to add
* @throws NullPointerException if unit is null
@@ -1414,7 +1381,7 @@ public final class UnitDatabase {
/**
* Adds to the list from a line in a unit file.
- *
+ *
* @param line line to look at
* @param lineCounter number of line, for error messages
* @since 2019-04-10
@@ -1432,14 +1399,14 @@ public final class UnitDatabase {
}
// divide line into name and expression
- final Matcher lineMatcher = NAME_EXPRESSION.matcher(line);
+ final var lineMatcher = NAME_EXPRESSION.matcher(line);
if (!lineMatcher.matches())
throw new IllegalArgumentException(String.format(
"Error at line %d: Lines of a unit file must consist of a unit name, then spaces or tabs, then a unit expression.",
lineCounter));
- final String name = lineMatcher.group(1);
+ final var name = lineMatcher.group(1);
- final String expression = lineMatcher.group(2);
+ final var expression = lineMatcher.group(2);
// this code should never occur
// if (name.endsWith(" ")) {
@@ -1453,18 +1420,15 @@ public final class UnitDatabase {
if (!this.containsUnitName(name))
throw new IllegalArgumentException(String
.format("! used but no unit found (line %d).", lineCounter));
+ } else if (name.endsWith("-")) {
+ final var prefixName = name.substring(0, name.length() - 1);
+ this.addPrefix(prefixName, this.getPrefixFromExpression(expression));
+ } else if (expression.contains(";")) {
+ // it's a multi-unit
+ this.addUnitSet(name, this.getUnitSetFromExpression(expression));
} else {
- if (name.endsWith("-")) {
- final String prefixName = name.substring(0, name.length() - 1);
- this.addPrefix(prefixName,
- this.getPrefixFromExpression(expression));
- } else if (expression.contains(";")) {
- // it's a multi-unit
- this.addUnitSet(name, this.getUnitSetFromExpression(expression));
- } else {
- // it's a unit, get the unit
- this.addUnit(name, this.getUnitFromExpression(expression));
- }
+ // it's a unit, get the unit
+ this.addUnit(name, this.getUnitFromExpression(expression));
}
}
@@ -1491,7 +1455,7 @@ public final class UnitDatabase {
/**
* Removes all units, unit sets, prefixes and dimensions from this database.
- *
+ *
* @since 2022-02-26
* @since v0.4.0
*/
@@ -1504,7 +1468,7 @@ public final class UnitDatabase {
/**
* Tests if the database has a unit dimension with this name.
- *
+ *
* @param name name to test
* @return if database contains name
* @since 2019-03-14
@@ -1516,7 +1480,7 @@ public final class UnitDatabase {
/**
* Tests if the database has a unit prefix with this name.
- *
+ *
* @param name name to test
* @return if database contains name
* @since 2019-01-13
@@ -1529,7 +1493,7 @@ public final class UnitDatabase {
/**
* Tests if the database has a unit with this name, taking prefixes into
* consideration
- *
+ *
* @param name name to test
* @return if database contains name
* @since 2019-01-13
@@ -1541,7 +1505,7 @@ public final class UnitDatabase {
/**
* Returns true iff there is a unit set with this name.
- *
+ *
* @param name name to check for
* @return true iff there is a unit set with this name
*
@@ -1564,7 +1528,7 @@ public final class UnitDatabase {
/**
* Evaluates a unit expression, following the same rules as
* {@link #getUnitFromExpression}.
- *
+ *
* @param expression expression to parse
* @return {@code LinearUnitValue} representing value of expression
* @since 2020-08-04
@@ -1583,7 +1547,7 @@ public final class UnitDatabase {
/**
* Gets a unit dimension from the database using its name.
- *
+ *
* @param name dimension's name
* @return dimension
* @since 2019-03-14
@@ -1591,12 +1555,11 @@ public final class UnitDatabase {
*/
public ObjectProduct<BaseDimension> getDimension(final String name) {
Objects.requireNonNull(name, "name must not be null.");
- final ObjectProduct<BaseDimension> dimension = this.dimensions.get(name);
+ final var dimension = this.dimensions.get(name);
if (dimension == null)
throw new NoSuchElementException(
"No dimension with name \"" + name + "\".");
- else
- return dimension;
+ return dimension;
}
/**
@@ -1611,7 +1574,7 @@ public final class UnitDatabase {
* multiplication)</li>
* <li>The operator '^' which exponentiates. Exponents must be integers.</li>
* </ul>
- *
+ *
* @param expression expression to parse
* @return parsed unit dimension
* @throws IllegalArgumentException if the expression cannot be parsed
@@ -1627,13 +1590,14 @@ public final class UnitDatabase {
if (this.containsDimensionName(expression))
return this.getDimension(expression);
- return this.unitDimensionParser.parseExpression(formatExpression(expression));
+ return this.unitDimensionParser
+ .parseExpression(formatExpression(expression));
}
/**
* Gets a unit. If it is linear, cast it to a LinearUnit and return it.
* Otherwise, throw an {@code IllegalArgumentException}.
- *
+ *
* @param name unit's name
* @return unit
* @since 2019-03-22
@@ -1650,26 +1614,25 @@ public final class UnitDatabase {
"Format nonlinear units like: unit(value).");
// solve the function
- final Unit unit = this.getUnit(parts.get(0));
- final double value = Double.parseDouble(
+ final var unit = this.getUnit(parts.get(0));
+ final var value = Double.parseDouble(
parts.get(1).substring(0, parts.get(1).length() - 1));
return LinearUnit.fromUnitValue(unit, value);
- } else {
- // get a linear unit
- final Unit unit = this.getUnit(name);
-
- if (unit instanceof LinearUnit)
- return (LinearUnit) unit;
- else
- throw new IllegalArgumentException(
- String.format("%s is not a linear unit.", name));
}
+ // get a linear unit
+ final var unit = this.getUnit(name);
+
+ if (unit instanceof LinearUnit)
+ return (LinearUnit) unit;
+ else
+ throw new IllegalArgumentException(
+ String.format("%s is not a linear unit.", name));
}
/**
* Gets a {@code LinearUnitValue} from a unit name. Nonlinear units will be
* converted to their base units.
- *
+ *
* @param name name of unit
* @return {@code LinearUnitValue} instance
* @since 2020-08-04
@@ -1687,7 +1650,7 @@ public final class UnitDatabase {
/**
* Gets a unit prefix from the database from its name
- *
+ *
* @param name prefix's name
* @return prefix
* @since 2019-01-10
@@ -1697,18 +1660,17 @@ public final class UnitDatabase {
try {
return UnitPrefix.valueOf(Double.parseDouble(name));
} catch (final NumberFormatException e) {
- final UnitPrefix prefix = this.prefixes.get(name);
+ final var prefix = this.prefixes.get(name);
if (prefix == null)
throw new NoSuchElementException(
"No prefix with name \"" + name + "\".");
- else
- return prefix;
+ return prefix;
}
}
/**
* Gets all of the prefixes that are on a unit name, in application order.
- *
+ *
* @param unitName name of unit
* @return prefixes
* @since 2020-08-26
@@ -1716,12 +1678,12 @@ public final class UnitDatabase {
*/
List<UnitPrefix> getPrefixesFromName(final String unitName) {
final List<UnitPrefix> prefixes = new ArrayList<>();
- String name = unitName;
+ var name = unitName;
while (!this.prefixlessUnits.containsKey(name)) {
// find the longest prefix
String longestPrefixName = null;
- int longestLength = name.length();
+ var longestLength = name.length();
while (longestPrefixName == null) {
longestLength--;
@@ -1734,7 +1696,7 @@ public final class UnitDatabase {
}
// longest prefix found!
- final UnitPrefix prefix = this.getPrefix(longestPrefixName);
+ final var prefix = this.getPrefix(longestPrefixName);
prefixes.add(0, prefix);
name = name.substring(longestLength);
}
@@ -1747,7 +1709,7 @@ public final class UnitDatabase {
* Currently, prefix expressions are much simpler than unit expressions: They
* are either a number or the name of another prefix
* </p>
- *
+ *
* @param expression expression to input
* @return prefix
* @throws IllegalArgumentException if expression cannot be parsed
@@ -1762,7 +1724,8 @@ public final class UnitDatabase {
if (this.containsUnitName(expression))
return this.getPrefix(expression);
- return this.prefixExpressionParser.parseExpression(formatExpression(expression));
+ return this.prefixExpressionParser
+ .parseExpression(formatExpression(expression));
}
/**
@@ -1770,13 +1733,13 @@ public final class UnitDatabase {
* @since 2020-08-26
* @since v0.3.0
*/
- public final Predicate<List<UnitPrefix>> getPrefixRepetitionRule() {
+ public Predicate<List<UnitPrefix>> getPrefixRepetitionRule() {
return this.prefixRepetitionRule;
}
/**
* Gets a unit from the database from its name, looking for prefixes.
- *
+ *
* @param name unit's name
* @return unit
* @since 2019-01-10
@@ -1784,27 +1747,28 @@ public final class UnitDatabase {
*/
public Unit getUnit(final String name) {
try {
- final double value = Double.parseDouble(name);
+ final var value = Double.parseDouble(name);
return Metric.ONE.times(value);
} catch (final NumberFormatException e) {
- final Unit unit = this.units.get(name);
+ final var unit = this.units.get(name);
if (unit == null)
throw new NoSuchElementException("No unit " + name);
- else if (unit.getPrimaryName().isEmpty())
+ if (unit.getPrimaryName().isEmpty())
return unit.withName(NameSymbol.ofName(name));
- else if (!unit.getPrimaryName().get().equals(name)) {
+ if (!unit.getPrimaryName().get().equals(name)) {
final Set<String> otherNames = new HashSet<>(unit.getOtherNames());
otherNames.add(unit.getPrimaryName().get());
return unit.withName(NameSymbol.ofNullable(name,
unit.getSymbol().orElse(null), otherNames));
- } else if (!unit.getOtherNames().contains(name)) {
+ }
+ if (!unit.getOtherNames().contains(name)) {
final Set<String> otherNames = new HashSet<>(unit.getOtherNames());
otherNames.add(name);
return unit.withName(
NameSymbol.ofNullable(unit.getPrimaryName().orElse(null),
unit.getSymbol().orElse(null), otherNames));
- } else
- return unit;
+ }
+ return unit;
}
}
@@ -1823,7 +1787,7 @@ public final class UnitDatabase {
* <li>A number which is multiplied or divided</li>
* </ul>
* This method only works with linear units.
- *
+ *
* @param expression expression to parse
* @return parsed unit
* @throws IllegalArgumentException if the expression cannot be parsed
@@ -1845,7 +1809,7 @@ public final class UnitDatabase {
/**
* Get a unit set from its name, throwing a {@link NoSuchElementException} if
* there is none.
- *
+ *
* @param name name of unit set
* @return unit set with that name
*
@@ -1853,7 +1817,7 @@ public final class UnitDatabase {
* @since v1.0.0
*/
public List<LinearUnit> getUnitSet(String name) {
- final List<LinearUnit> unitSet = this.unitSets.get(name);
+ final var unitSet = this.unitSets.get(name);
if (unitSet == null)
throw new NoSuchElementException("No unit set with name " + name);
return unitSet;
@@ -1866,20 +1830,19 @@ public final class UnitDatabase {
* @since v1.0.0
*/
List<LinearUnit> getUnitSetFromExpression(String expression) {
- final String[] parts = expression.split(";");
+ final var parts = expression.split(";");
final List<LinearUnit> units = new ArrayList<>(parts.length);
for (final String unitName : parts) {
- final Unit unit = this.getUnitFromExpression(unitName.trim());
+ final var unit = this.getUnitFromExpression(unitName.trim());
- if (!(unit instanceof LinearUnit)) {
+ if (!(unit instanceof LinearUnit))
throw new IllegalArgumentException(String.format(
"Unit '%s' is in a unit-set expression, but is not linear.",
unitName));
- } else if (units.size() > 0 && !unit.canConvertTo(units.get(0))) {
+ if (units.size() > 0 && !unit.canConvertTo(units.get(0)))
throw new IllegalArgumentException(String.format(
"Units in expression '%s' have different dimensions.",
expression));
- }
units.add((LinearUnit) unit);
}
@@ -1904,7 +1867,7 @@ public final class UnitDatabase {
* no unit is found, an IllegalArgumentException is thrown. This is used to
* define initial units and ensure that the database contains them.</li>
* </ul>
- *
+ *
* @param file file to read
* @throws NullPointerException if file is null
* @return list of errors that happened when loading file
@@ -1915,7 +1878,7 @@ public final class UnitDatabase {
Objects.requireNonNull(file, "file must not be null.");
final List<LoadingException> errors = new ArrayList<>();
try {
- long lineCounter = 0;
+ var lineCounter = 0L;
for (final String line : Files.readAllLines(file)) {
try {
this.addDimensionFromLine(line, ++lineCounter);
@@ -1944,10 +1907,10 @@ public final class UnitDatabase {
public List<LoadingException> loadDimensionsFromStream(
final InputStream stream) {
final List<LoadingException> errors = new ArrayList<>();
- try (final Scanner scanner = new Scanner(stream)) {
- long lineCounter = 0;
+ try (final var scanner = new Scanner(stream)) {
+ var lineCounter = 0L;
while (scanner.hasNextLine()) {
- final String line = scanner.nextLine();
+ final var line = scanner.nextLine();
try {
this.addDimensionFromLine(line, ++lineCounter);
} catch (IllegalArgumentException | NoSuchElementException e) {
@@ -1976,7 +1939,7 @@ public final class UnitDatabase {
* no unit is found, an IllegalArgumentException is thrown. This is used to
* define initial units and ensure that the database contains them.</li>
* </ul>
- *
+ *
* @param file file to read
* @throws NullPointerException if file is null
* @return list of errors that happened when loading file
@@ -1987,7 +1950,7 @@ public final class UnitDatabase {
Objects.requireNonNull(file, "file must not be null.");
final List<LoadingException> errors = new ArrayList<>();
try {
- long lineCounter = 0;
+ var lineCounter = 0L;
for (final String line : Files.readAllLines(file)) {
try {
this.addUnitOrPrefixFromLine(line, ++lineCounter);
@@ -2015,10 +1978,10 @@ public final class UnitDatabase {
*/
public List<LoadingException> loadUnitsFromStream(InputStream stream) {
final List<LoadingException> errors = new ArrayList<>();
- try (final Scanner scanner = new Scanner(stream)) {
- long lineCounter = 0;
+ try (final var scanner = new Scanner(stream)) {
+ var lineCounter = 0L;
while (scanner.hasNextLine()) {
- final String line = scanner.nextLine();
+ final var line = scanner.nextLine();
try {
this.addUnitOrPrefixFromLine(line, ++lineCounter);
} catch (IllegalArgumentException | NoSuchElementException e) {
@@ -2039,10 +2002,9 @@ public final class UnitDatabase {
public Map<String, UnitPrefix> prefixMap(boolean includeDuplicates) {
if (includeDuplicates)
return Collections.unmodifiableMap(this.prefixes);
- else
- return Collections.unmodifiableMap(ConditionalExistenceCollections
- .conditionalExistenceMap(this.prefixes,
- entry -> !isRemovableDuplicate(this.prefixes, entry)));
+ return Collections.unmodifiableMap(ConditionalExistenceCollections
+ .conditionalExistenceMap(this.prefixes,
+ entry -> !isRemovableDuplicate(this.prefixes, entry)));
}
/**
@@ -2050,7 +2012,7 @@ public final class UnitDatabase {
* @since 2020-08-26
* @since v0.3.0
*/
- public final void setPrefixRepetitionRule(
+ public void setPrefixRepetitionRule(
Predicate<List<UnitPrefix>> prefixRepetitionRule) {
this.prefixRepetitionRule = prefixRepetitionRule;
}
@@ -2089,7 +2051,7 @@ public final class UnitDatabase {
* {@link PrefixedUnitMap#values() values()} methods currently ignore
* prefixes.
* </p>
- *
+ *
* @return a map mapping unit names to units, including prefixed names
* @since 2019-04-13
* @since v0.2.0
@@ -2110,11 +2072,9 @@ public final class UnitDatabase {
public Map<String, Unit> unitMapPrefixless(boolean includeDuplicates) {
if (includeDuplicates)
return Collections.unmodifiableMap(this.prefixlessUnits);
- else
- return Collections.unmodifiableMap(ConditionalExistenceCollections
- .conditionalExistenceMap(this.prefixlessUnits,
- entry -> !isRemovableDuplicate(this.prefixlessUnits,
- entry)));
+ return Collections.unmodifiableMap(ConditionalExistenceCollections
+ .conditionalExistenceMap(this.prefixlessUnits,
+ entry -> !isRemovableDuplicate(this.prefixlessUnits, entry)));
}
/**