I have two arrays say original[] and input[]. In the first array i have 3 values
1
2
3
and in the second array i give 2 values
2
3
I want to check if these two values are present in the first array How can i do this?
6 Answers 6
Integer original[] = {1,2,3};
Integer input[] = {2,3};
if (Arrays.asList(original).containsAll(Arrays.asList(input)))
{
System.out.println("Yup, they're in there!");
}
Note that this won't work on primitive (int) arrays; you have to box them in Integer
objects. If your arrays are String[]
you're golden.
-
Gah, sorry - was doing this from memory, and the memory failed ... editingBrian Roach– Brian Roach2011年03月25日 05:50:55 +00:00Commented Mar 25, 2011 at 5:50
I want to check if these two values are present in the first array How can i do this?
Iterate your second array and check it against the elements of first one.
-
@Xan: if the OP asked for some code, this question would have been closed.Prince John Wesley– Prince John Wesley2012年07月24日 15:43:18 +00:00Commented Jul 24, 2012 at 15:43
-
Maybe he didn't check his email? Or he don't care?acorello– acorello2012年07月24日 16:02:42 +00:00Commented Jul 24, 2012 at 16:02
If the larger array is sorted, check out the binarySearch methods in http://download.oracle.com/javase/1.4.2/docs/api/java/util/Arrays.html
Iterate through your second array and search for each one in the array.
If you're interested in the query "is the value X contained in my array?," then you might want to considered switching data structures. Arrays are good for storing finite lists of elements in sequence, and the main properties of array elements are their positions. If you want to store the elements so that you can easily check whether or not a given element is present, I'd strongly suggest switching to storing the elements in a Set
, since this interface more naturally supports this idea. Moreover, both HashSet
and TreeSet
can do lookup queries faster than a standard search over an array.
That said, if you must stick with arrays, then any of the other answers here should be perfectly fine. I'd just suggest reevaluating whether or not you should be using arrays in the first place.
Take the first array apply the search logic onto it by getting one element form your second array and repeat this until the last element not finished. You will get help from this link how to make search in array. http://www.roseindia.net/java/beginners/OccurancesInArray.shtml
for(int i=0;i<=orignal.length;i++) {
if(orignal[0]==input[i] | orignal[0]==input[++i]) {
System.out.println("Yup, they're in there!");
}
}
This will surely work.