开发者

Check if all values in one array are present in another

开发者 https://www.devze.com 2023-02-19 10:26 出处:网络
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

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?


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.


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.


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.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号