ビットオーバーキルですが、これは拡張可能である必要があります。
注意:私は乗数ルックアップのみをカバーしました。
/**
* Possible units and their multipliers.
*/
enum Unit {
Unit(1),
Hundred(100),
Thousand(1000),
Million(1000000),
Billion(1000000000),
Squillion(Integer.MAX_VALUE);
private final int multiplier;
Unit(int multiplier) {
this.multiplier = multiplier;
}
}
/**
* Comparator that matches caseless and plurals
*
* NB: Not certain if this is consistent.
*/
private static final Comparator<String> COMPARECASELESSANDPLURALS
= (String o1, String o2) -> {
// Allow case difference AND plurals.
o1 = o1.toLowerCase();
o2 = o2.toLowerCase();
int diff = o1.compareTo(o2);
if (diff != 0) {
// One character different in length?
if (Math.abs(o1.length() - o2.length()) == 1) {
// Which may be plural?
if (o1.length() > o2.length()) {
// o1 might be plural.
if (o1.endsWith("s")) {
diff = o1.substring(0, o1.length() - 1).compareTo(o2);
}
} else if (o2.endsWith("s")) {
// o2 might be plural.
diff = -o2.substring(0, o2.length() - 1).compareTo(o1);
}
}
}
return diff;
};
// Build my lookup.
static final Map<String, Integer> MULTIPLIERS
= Arrays.stream(Unit.values())
// Collect into a Map
.collect(Collectors.toMap(
// From name of the enum.
u -> u.name(),
// To its multiplier.
u -> u.multiplier,
// Runtime exception in case of duplicates.
(k, v) -> {
throw new RuntimeException(String.format("Duplicate key %s", k));
},
// Use a TreeMap that ignores case and plural.
() -> new TreeMap(COMPARECASELESSANDPLURALS)));
// Gives the multiplier for a word.
public Optional<Integer> getMultiplier(String word) {
return Optional.ofNullable(MULTIPLIERS.get(word));
}
public void test() {
String[] tests = {"Million", "Millions", "Thousand", "Aardvark", "billion", "billions", "squillion"};
for (String s : tests) {
System.out.println("multiplier(" + s + ") = " + getMultiplier(s).orElse(1));
}
}
何百万もの整数を整数に変換したときに、なぜ「ミリオン」を表示したいのですか? – sauumum
私は何もまだ整数に変換していません。私はページ上の要素にアクセスし、そのテキストを取得するためにgetText()プロパティを使用しました。今私がそれを印刷すると、それは3.3百万を表示します。 私が望むのは、文字列 '3.3 Millions'の数(3.3)を整数に変換して、ハッシュマップをソートして、その人口あたりの上位3つの国を見つけることです。 私の目標は、結果を次のように記録することです。 例、上位の人口は3.3億人の(ある国)です。 – Uziii
ここまで来ました。今度は3.3百万を3.3 * 1000000に変更してCollectionに入れて、この値をソートできるようにします。値がソートされると、値を何らかの順序(昇順/降順)で印刷します。ここでは、 "3.3百万"または "3300000"を印刷しますか? – sauumum