在键值对的 PCollection 中查找具有最大值的键
Finding the key with maximum value in a PCollection of key-value pairs
我有 PCollection
个 KV<String,Integer>
项,我想找到其中值最大的对。
例如,如果键值对是
{foo:3,bar:2,baz:7}
那么结果将是一对 baz:7
.
None Max class 中的方法似乎完全符合我的要求:
Max.integersPerKey
给出了 PCollection
个键值对,这些键值对与输入中的每个键相关联;我只想要一个全球最高价值的单品
Max.integersGlobally
需要 PCollection
个整数;它不需要键值对。从 KV 对映射到值然后使用它会给出最高值,但我也想保留与该值关联的键。
当您使用 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())));
我有 PCollection
个 KV<String,Integer>
项,我想找到其中值最大的对。
例如,如果键值对是
{foo:3,bar:2,baz:7}
那么结果将是一对 baz:7
.
None Max class 中的方法似乎完全符合我的要求:
Max.integersPerKey
给出了PCollection
个键值对,这些键值对与输入中的每个键相关联;我只想要一个全球最高价值的单品Max.integersGlobally
需要PCollection
个整数;它不需要键值对。从 KV 对映射到值然后使用它会给出最高值,但我也想保留与该值关联的键。
当您使用 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())));