如何使用流编写模式方法

时间:2015-11-29 03:33:34

标签: java generics java-8 java-stream

我正在尝试使用Collection编写一个方法来获取Comparator的模式。

请有人能告诉我为了编译这些我需要做些什么改变吗?我不想改变签名。

static <T> T mode(Collection<? extends T> collection, Comparator<? super T> comparator) {
    return collection.stream()
                     .collect(Collectors.groupingBy(t -> t, () -> new TreeMap<>(comparator), Collectors.counting()))
                     .entrySet()
                     .stream()
                     .reduce(BinaryOperator.maxBy(Comparator.comparingLong(Map.Entry::getValue)))
                     .map(Map.Entry::getKey)
                     .orElseThrow(IllegalArgumentException::new);
}

修改

事实证明我只是使用了错误的版本。这不能使用javac 1.8.0_25进行编译。确切的三条错误消息是:

Error:(40, 47) java: incompatible types: inferred type does not conform to upper bound(s)
inferred: java.lang.Object
upper bound(s): T,java.lang.Object

Error:(43, 45) java: incompatible types: cannot infer type-variable(s) T
(argument mismatch; invalid method reference
  method getValue in interface java.util.Map.Entry<K,V> cannot be applied to given types
    required: no arguments
    found: java.lang.Object
    reason: actual and formal argument lists differ in length)

Error:(44, 25) java: invalid method reference
non-static method getKey() cannot be referenced from a static context

但是,我已经升级到javac 1.8.0_65并且编译得很完美。

1 个答案:

答案 0 :(得分:4)

此代码不能在Java 8u40之前使用javac进行编译。如果您仍想使其与旧的javac版本兼容,您可以引入另一个通用变量:

static <T> T mode(Collection<? extends T> collection, Comparator<? super T> comparator) {
    return mode0(collection, comparator);
}

private static <T, TT extends T> T mode0(Collection<TT> collection,
                                         Comparator<? super T> comparator) {
    return collection.stream()
                     .collect(Collectors.groupingBy(t -> t, 
                                  () -> new TreeMap<>(comparator), 
                                  Collectors.counting()))
                     .entrySet()
                     .stream()
                     .reduce(BinaryOperator.maxBy(
                                  Comparator.comparingLong(Map.Entry::getValue)))
                     .map(Map.Entry::getKey)
                     .orElseThrow(IllegalArgumentException::new);
}

顺便说一下,您可以使用Stream.max代替reduceMap.Entry.comparingByValue()比较器:

private static <T, TT extends T> T mode0(Collection<TT> collection,
                                         Comparator<? super T> comparator) {
    return collection.stream()
                     .collect(Collectors.groupingBy(t -> t, 
                                  () -> new TreeMap<>(comparator), 
                                  Collectors.counting()))
                     .entrySet()
                     .stream()
                     .max(Map.Entry.comparingByValue())
                     .map(Map.Entry::getKey)
                     .orElseThrow(IllegalArgumentException::new);
}