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可以映射到10和。可能,计数可能相同。USD1

现在我有没有尽可能简洁并有能力使用java-8,得到InvoiceCurrency属于最高数字的那个?有没有一种简洁的方法来查看排序整数计数的前 2 个实际上具有相同的值?

我知道我可以用循环等方式对其进行编程,但我希望依靠这种java-8精神来编写最可维护的代码。

4

1 回答 1

1

Map<String, Integer>带有 a但相同的简单示例将适用于您的示例。打印前 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 回答