【发布时间】:2021-11-28 16:01:19
【问题描述】:
我想从列表中检索仅重复 x 次的重复项。我不知道怎么做,我只设法得到所有重复项。
【问题讨论】:
-
跟踪条目出现的次数?听起来像是某种 key => value 数据结构可能有用的东西。
-
你能分享你的代码吗?这是作业题吗?
我想从列表中检索仅重复 x 次的重复项。我不知道怎么做,我只设法得到所有重复项。
【问题讨论】:
将每个元素的频率计入映射Map<MyObject, Integer>,然后按所需频率从映射中选择条目。
方法hashCode 和equals 必须在MyObject 类中正确实现:
public static List<MyObject> findDuplicates(int frequency, List<MyObject> input) {
return input
.stream()
.collect(Collectors.groupingBy(x -> x, Collectors.summingInt(x -> 1))) // Map<MyObject, Integer>
.entrySet()
.stream() // Stream<Map.Entry<MyObject, Integer>>
.filter(e -> e.getValue() == frequency)
.map(Map.Entry::getKey) // Stream<MyObject>
.collect(Collectors.toList());
}
非流实现将构建频率图,然后对其进行迭代以填充过滤列表和/或打印匹配的重复元素:
public static List<MyObject> findDuplicates(int frequency, List<MyObject> input) {
Map<MyObject, Integer> frequencies = new LinkedHashMap<>();
for (MyObject mo : input) {
frequencies.merge(mo, 1, Integer::sum);
}
List<MyObject> result = new ArrayList<>();
frequencies.forEach((mo, freqValue) -> {
if (freqValue == frequency) {
result.add(mo);
// System.out.printlnm("Found: " + mo);
}
});
return result;
}
【讨论】:
这是一个伪代码中的 3 行算法:
FOR each element "e" of collection "x"
INCREMENT the count for "e"
ENDFOR
我们可以通过多种方式在 Java 中实现这一点。例如,Map:
public static <T> Map<T, Integer> countDuplicates(Collection<T> collection) {
Map<T, Integer> duplicateCounts = new HashMap<>();
for(T element : collection) {
// Map#putIfAbsent will put the entry (element, 1) iff the map does NOT already contain the key "element".
// If the map already contains the key "element", it returns the current value (element, ?).
Integer duplicateCount = duplicateCounts.putIfAbsent(element, 1);
if(duplicateCount != null) {
duplicateCounts.put(element, duplicateCount + 1);
}
}
return duplicateCounts;
}
【讨论】: