Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

java

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?

like image 814
Chris Headleand Avatar asked Jan 06 '13 00:01

Chris Headleand


2 Answers

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 ");
} 
like image 107
Survivor Avatar answered Oct 07 '22 13:10

Survivor


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;
}
like image 23
user3690146 Avatar answered Oct 07 '22 14:10

user3690146