查找重复次数超过3次的ID

时间:2014-08-06 12:35:06

标签: java

我需要找到重复超过3次的repeatedLateComersId。 lateComers包含可能重复超过3次的客户列表。

 List<Long> repeatedLateComersId=new ArrayList<Long>();
    for (Customer repeatedLateComers : lateComers) {
        repeatedLateComersId.add(repeatedLateComers.getId());
    }

请帮帮我。

3 个答案:

答案 0 :(得分:2)

您可以使用Collections#frequency查找集合中出现的次数。

例如:

int i = Collections.frequency(list, "obj"); //This will return String obj's occurrences in list

答案 1 :(得分:1)

这是你想要的吗?

Map<Long, Integer> counts = new HashMap<>(); // Tracks how many times each ID is found
List<Long> repeatedLateComersId = new ArrayList<>(); // Final output will be stored here
for (Customer lateComer : lateComers) {
    long id = lateComer.getId();

    // This updates the count:
    Integer count = counts.get(id);
    if (count == null) count = 0;
    count++;
    counts.put(id, count);

    if (count == 3) {
        // When we've encountered this three times, add it to the list
        repeatedLateComersId.add(id);
    }
}

答案 2 :(得分:0)

在遍历后来者名单时,检查当前的后来者是否有超过3的频率。如果是这样,请添加到重复的后来者名单中。

 List<Long> repeatedLateComersId=new ArrayList<Long>();
    for (Customer lateComer: lateComers) {
        if (Collections.frequency(lateComers, lateComer) > 3) {
            repeatedLateComersId.add(lateComer.getId());
        }
    }