3

I have two different String array.

String[] str1={(ABC),(CDE),(DEF),(FGE),(ERT)};

String[] str2={(ABC),(FGE)};

I wanna know is str1 have str2's all members?How can i search str2 in str1?

1
  • 1
    Did you mean "ABC", instead of (ABC), etc.? Commented Apr 28, 2011 at 22:15

3 Answers 3

6
Arrays.asList(str1).containsAll(Arrays.asList(str2));
Sign up to request clarification or add additional context in comments.

Comments

2

Create one Set object for each of your arrays containing the elements of the array. Then use the Set class's containsAll method to check that the one Set contains all of the elements from the other Set.

http://download.oracle.com/javase/6/docs/api/java/util/Set.html

2 Comments

You need only a Set (i.e. a structure with fast contains check) for the bigger array, for the other one a List (like Arrays.asList()) works too without loosing efficiency. (And it should be a HashSet or TreeSet. Most efficiently if you can reuse it instead of recreating it for each search.)
@Paŭlo Ebermann Good addition (the comment about HashSet). Although a Set may only have benefits for larger arrays, I think that it is overall a better solution than mportiz08 posted, since the choice of Set or List really doesn't matter for smaller input.
1

You could search each and every element of str2 in str1. Or, more efficiently: sort str1, and use binary search.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.