如何使用过滤器、收集器等以适当的 Java 8 功能样式重写以下内容:
private BigInteger calculateProduct(char[] letters) {
int OFFSET = 65;
BigInteger[] bigPrimes = Arrays.stream(
new int[] { 2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31,
37, 41, 43, 47, 53, 59, 61, 67, 71, 73, 79, 83, 89,
97, 101, 103, 107, 109, 113 })
.mapToObj(BigInteger::valueOf)
.toArray(BigInteger[]::new);
BigInteger result = BigInteger.ONE;
for (char c : letters) {
//System.out.println(c+"="+(int)c);
if (c < OFFSET) {
return new BigInteger("-1");
}
int pos = c - OFFSET;
result = result.multiply(bigPrimes[pos]);
}
return result;
}
@Test public void test() {
assertThat(calculateProduct(capitalize("carthorse"))).isEqualTo(calculateProduct(capitalize("orchestra")));
}
private char[] capitalize(String word) {
return word.toUpperCase().toCharArray();
}