-3

I have 2 String arrays say A and B. both contains some strings. I want to compare array A with B to find the elements which are exist in both arrays.....

String[] a=new String[] {"alpha","beta"};
String[] b=new String[] {"alpha","beta","gamma","xxxx","yyyy"};

the result which I needed is alpha and beta...

Cœur
  • 34,719
  • 24
  • 185
  • 251
  • Good luck and have fun! When you have an specific question that meets our guidelines, feel free to ask it. Check the FAQ, and look if a similar question has already been answered. Meanwhile, voting to close this question as off-topic. – SJuan76 Oct 04 '15 at 11:14
  • [Questions asking for homework help must include a **summary of the work you've done so far to solve the problem**, and a **description of the difficulty you are having solving it**.](http://stackoverflow.com/help/on-topic) – Pshemo Oct 04 '15 at 11:23

2 Answers2

0

You can use retainAll method from Collection.

String[] a=new String[] {"alpha","beta"};
String[] b=new String[] {"alpha","beta","gamma","xxxx","yyyy"};
HashSet<String> set1 = new HashSet<String>(Arrays.asList(a));
HashSet<String> set2 = new HashSet<String>(Arrays.asList(b));
set1.retainAll(set2);
System.out.println(set1);     //Output : [alpha, beta]
2787184
  • 3,531
  • 8
  • 43
  • 76
0

If you want the intersection of two arrays, you can have a look here : Java, find intersection of two arrays.

Community
  • 1
  • 1
Gaël J
  • 7,665
  • 4
  • 16
  • 29