繁体   English   中英

是否有可能找出一个值在数组列表中是否存在两次?

[英]Is it possible to find out if a value exists twice in an arraylist?

我有一个整数数组列表..

ArrayList <Integer> portList = new ArrayList();

我需要检查是否已经输入了两次特定的整数。 这在Java中可能吗?

您可以使用类似这样的东西来查看特定值出现的次数:

System.out.println(Collections.frequency(portList, 1));
// there can be whatever Integer, i put 1 so you can understand

并检查特定值是否不止一次存在,您可以使用以下内容:

if ( (Collections.frequency(portList, x)) > 1 ){
    System.out.println(x + " is in portList more than once ");
} 

这将告诉您ArrayList是否至少有两个相同的值

int first = portList.indexOf(someIntValue);
int last  = portList.lastIndexOf(someIntValue);
if (first != -1 && first != last) {
    // someIntValue exists more than once in the list (not sure how many times though)
}

**编辑**

如果您真的想知道给定值有多少重复项,则需要遍历整个数组。 像这样的事情:

/**
 * Will return a list of all indexes where the given value
 * exists in the given array. The list will be empty if the
 * given value does not exist at all.
 *
 * @param List<E> list
 * @param E value
 * @return List<Integer>    a list of indexes in the list
 */
public <E> List<Integer> collectFrequency(List<E> list, E value) {
   ArrayList<Integer> freqIndex = new ArrayList<Integer>();
   E item;
   for (int i=0, len=list.size(); i<len; i++) {
       item = list.get(i);
       if ((item == value) || (null != item && item.equals(value))) {
           freqIndex.add(i);
       }
   }
   return freqIndex;
}

if (!collectFrequency(portList, someIntValue).size() > 1) {
    // duplicate value
}

或者干脆

if (Collections.frequency(portList, someIntValue) > 1) {
    // duplicate value
}

如果你想用一种方法来做到这一点,那么不。 但是,如果您需要简单地找出它在列表中至少存在一次,则可以分 2 个步骤。 你可以做

int first = list.indexOf(object)
int second = list.lastIndexOf(object) 
//Don't forget to also check to see if either are -1, the value does not exist at all.
if (first == second) {
    // No Duplicates of object appear in the list
} else {
    // Duplicate exists
}

我知道这是一个老问题,但既然我在这里寻找答案,我想我会分享我的解决方案

public static boolean moreThanOnce(ArrayList<Integer> list, int searched) 
{
    int numCount = 0;

    for (int thisNum : list) {
        if (thisNum == searched) numCount++;
    }

    return numCount > 1;
}
Set portSet = new HashSet<Integer>();
portSet.addAll(portList);
boolean listContainsDuplicates = portSet.size() != portList.size();

我使用以下解决方案找出 ArrayList 是否不止一次包含一个数字。 此解决方案与上面user3690146列出的解决方案非常接近,但根本不使用辅助变量。 运行它后,您会收到“该号码被多次列出”作为返回消息。

public class Application {

    public static void main(String[] args) {

        ArrayList<Integer> list = new ArrayList<Integer>();

        list.add(4);
        list.add(8);
        list.add(1);
        list.add(8);

        int number = 8;

        if (NumberMoreThenOnceInArray(list, number)) {
            System.out.println("The number is listed more than once");
        } else {
            System.out.println("The number is not listed more than once");
        }
    }

    public static boolean NumberMoreThenOnceInArray(ArrayList<Integer> list, int whichNumber) {

        int numberCounter = 0;

        for (int number : list) {
            if (number == whichNumber) {
                numberCounter++;
            }
        }

        if (numberCounter > 1) {
            return true;
        }

        return false;
    }

}

这是我的解决方案(在 Kotlin 中)

    // getItemsMoreThan(list, 2) -> [4.45, 333.45, 1.1, 4.45, 333.45, 2.05, 4.45, 333.45, 2.05, 4.45] -> {4.45=4, 333.45=3}
    // getItemsMoreThan(list, 1)->  [4.45, 333.45, 1.1, 4.45, 333.45, 2.05, 4.45, 333.45, 2.05, 4.45] -> {4.45=4, 333.45=3, 2.05=2}
    fun getItemsMoreThan(list: List<Any>, moreThan: Int): Map<Any, Int> {
        val mapNumbersByElement: Map<Any, Int> = getHowOftenItemsInList(list)
        val findItem = mapNumbersByElement.filter { it.value > moreThan }
        return findItem
    }

    // Return(map) how often an items is list.
    // E.g.: [16.44, 200.00, 200.00, 33.33, 200.00, 0.00] -> {16.44=1, 200.00=3, 33.33=1, 0.00=1}
    fun getHowOftenItemsInList(list: List<Any>): Map<Any, Int> {
        val mapNumbersByItem = list.groupingBy { it }.eachCount()
        return mapNumbersByItem
    }

通过看问题,我们需要找出一个在一个ArrayList中是否存在两次 所以我相信我们可以通过下面的简单检查来减少“遍历整个列表只是为了检查该值是否只存在两次”的开销

public boolean moreThanOneMatch(int number, ArrayList<Integer> list) {

    int count = 0;
    for (int num : list) {
        if (num == number) {
            count ++ ;
            if (count == 2) {
                return true;
            }
        }
    }
    return false;
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM