【问题标题】:How can i find duplicates in List repeated x times?如何在重复 x 次的列表中找到重复项?
【发布时间】:2021-11-28 16:01:19
【问题描述】:

我想从列表中检索仅重复 x 次的重复项。我不知道怎么做,我只设法得到所有重复项。

【问题讨论】:

  • 跟踪条目出现的次数?听起来像是某种 key => value 数据结构可能有用的东西。
  • 你能分享你的代码吗?这是作业题吗?

标签: java list


【解决方案1】:

将每个元素的频率计入映射Map<MyObject, Integer>,然后按所需频率从映射中选择条目。

方法hashCodeequals 必须在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;
}

【讨论】:

    【解决方案2】:

    这是一个伪代码中的 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;
    }
    

    【讨论】:

      猜你喜欢
      • 2013-04-12
      • 1970-01-01
      • 2013-02-21
      • 1970-01-01
      • 2013-03-29
      • 2014-09-03
      • 1970-01-01
      • 2021-12-26
      • 2019-01-15
      相关资源
      最近更新 更多