在键值对的 PCollection 中查找具有最大值的键

Finding the key with maximum value in a PCollection of key-value pairs

我有 PCollectionKV<String,Integer> 项,我想找到其中值最大的对。

例如,如果键值对是 {foo:3,bar:2,baz:7} 那么结果将是一对 baz:7.

None Max class 中的方法似乎完全符合我的要求:

当您使用 Max.of(comparator) 并实现一个比较器来比较 KV<String,Integer> 的值时,它应该可以工作。

这样的比较器可以如下所示:

 public static class KVComparator implements Comparator<KV<String,Integer>>, Serializable {
        @Override
        public int compare(KV<String, Integer> o1, KV<String, Integer> o2) {
         return   o1.getValue().compareTo(o2.getValue());
        }
    }

当你有 PCollection<KV<String,Integer>> p 时,它看起来像这样:

 p.apply(Combine.globally(Max.of(new KVComparator())));