簡體   English   中英

如何在重復 x 次的列表中找到重復項?

[英]How can i find duplicates in List repeated x times?

我想從列表中檢索僅重復 x 次的重復項。 我不知道該怎么做,我只設法得到所有重復項。

將每個元素的頻率計數到 map Map<MyObject, Integer>然后 select 按所需頻率計算來自 map 的條目。

方法hashCodeequals必須在 class 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());
}

非流實現將構建頻率 map 然后迭代它以填充過濾列表和/或打印匹配的重復元素:

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;
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM