1

私はすでに次のものを持っています:

public enum InvoiceCurrency {
    EUR(
            s -> (s.contains("€") || s.contains("EUR"))
    ),
    USD(
            s -> (s.contains("$") || s.contains("USD"))
    );

    private final Predicate<String> predicate;

    InvoiceCurrency(final Predicate<String> predicate) {
        this.predicate = predicate;
    }

    public boolean matchesString(final String value) {
        return predicate.test(value);
    }

    public static EnumMap<InvoiceCurrency, Integer> createMapping(final Stream<String> valuesStream) {
        EnumMap<InvoiceCurrency, Integer> mapping = new EnumMap<>(InvoiceCurrency.class);
        mapping.replaceAll((k, v) -> 0);
        Stream<InvoiceCurrency> enums = Arrays.stream(InvoiceCurrency.values());
        valuesStream.forEach(
            s -> enums.forEach(
                e -> {
                    if (e.matchesString(s)) {
                        mapping.compute(e, (k, v) -> v++);
                    }
                }
            )
        );
        return mapping;
    }
}

private InvoiceCurrency calculateCurrency() {
    EnumMap<InvoiceCurrency, Integer> map = InvoiceCurrency.createMapping(data.words.stream().map(w -> w.content));
    InvoiceCurrency maximum = map.entrySet().parallelStream().  //how to continue?
}

これにより、列挙型から「出現回数」へのマッピングが行われるため、 およびにEURマッピングできます。おそらく、カウントは同じかもしれません。10USD1

できるだけ簡潔に、そして を使用する能力があれば、最大数に属する をjava-8取得する必要がありますか? InvoiceCurrencyそして、ソートされた整数カウントの上位2つが実際に同じ値であることを確認する簡潔な方法はありますか?

java-8ループなどでプログラムできることはわかっていますが、最も保守しやすいコードの精神に頼りたいと思っています。

4

1 に答える 1

1

a を使用した簡単な例ですMap<String, Integer>が、あなたの例でも同じことが機能します。上位 2 つのエントリ (b と c または d) を出力します。

import static java.util.Collections.reverseOrder;
import static java.util.Comparator.comparingInt;
//...

Map<String, Integer> map = new HashMap<>();
map.put("a", 2);
map.put("b", 10);
map.put("c", 5);
map.put("d", 5);
map.put("e", 1);

map.entrySet().parallelStream()
        .sorted(reverseOrder(comparingInt(Map.Entry::getValue)))
        .limit(2)
        .forEach(System.out::println);

//or:   .forEachOrdered(System.out::println);
//to print in descending order

注: b129 以降では、sorted(comparingInt(Map.Entry::getValue).reversed())の代わりに を使用することもできますsorted(reverseOrder(comparingInt(Map.Entry::getValue)))

于 2014-02-13T10:23:21.680 に答える