简体   繁体   中英

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

I have an integer arraylist..

ArrayList <Integer> portList = new ArrayList();

I need to check if a specific integer has already been entered twice. Is this possible in Java?

You could use something like this to see how many times a specific value is there:

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

And to check if a specific value is there more than once you could use something like this:

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

This will tell you if you have at least two same values in your 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)
}

** Edit **

If you really want to know how many duplicates of a given value you have, you need to iterate through the entire array. Something like this :

/**
 * 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
}

Or simply

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

If you are looking to do this in one method, then no. However, you could in 2 steps if you need to simple find out of it exists at least more then once in the List. You could do

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
}

I know it's an old question, but since I was here looking for the answer, I thought I'd share MY solution

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();

I used the following solution th find out whether an ArrayList contains a number more than once. This solution comes very close to the one listed by user3690146 above, but does not use a helper variable at all. After running it, you get "The number is listed more than once" as a return message.

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

}

Here my solution (in 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
    }

By looking at the question, we need to find out whether a value exists twice in an ArrayList. So I believe that we can reduce the overhead of "going through the entire list just to check whether the value only exists twice" by doing the simple check below.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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