1

Let's say I have two arrays,

String[] A= {"1", "2", "3", "4", "5", "6", "7", "8", "9", "10"};

String[] B= {"0", "2", "4", "6", "8", "10", "12"};

How can I compare the two arrays, in a way that I want to return another array with all the values of A that are in B?

Returning array: String[] C= {"2", "4", "6","8","10"};


I read this stackoverflow question which essentially, is asking the same thing - but would like to know what the equivalent is, in Java

C# code from answer:

string[] a1 = { "A","B", "C", "D" };
string[] a2 = { "A", "E", "I", "M", "Q", "U" ,"Y" };
string[] result = a1.Where(a2.Contains).ToArray();
Jett
  • 781
  • 1
  • 14
  • 30
  • BTW in C# there's no need to use `a1.Where(a2.Contains).ToArray();` over simply doing `a1.Intersect(a2);`. The latter is clearly shorter and more readable. – Ousmane D. Sep 23 '19 at 20:34

3 Answers3

3

using the stream API, you could do:

String[] result = Arrays.stream(a1)
                        .filter(new HashSet<>(Arrays.asList(a2))::contains)
                        .toArray(String[]::new); 

Edit:

just for those curious about whether a new set will be constructed for each element, this is not the case at all.

only one Set instance is constructed, the above code is equivalent to:

List<String> list = new ArrayList<>();
HashSet<String> strings = new HashSet<>(Arrays.asList(a2));
for (String s : a1) { 
   if (strings.contains(s)) list.add(s); 
}
String[] result = list.toArray(new String[0]);
Ousmane D.
  • 54,915
  • 8
  • 91
  • 126
2
Set<String> a = new HashSet<>(Arrays.asList(a1));
Set<String> b = new HashSet<>(Arrays.asList(a2));
a.retainAll(b);
String[] results = a.toArray(new String[a.size()]);
pholser
  • 4,908
  • 1
  • 27
  • 37
0

Comparison works with below Statement:

   System.out.println("is A equals to B: " + Arrays.equals(A, B));
   String [] joined = ObjectArrays.concat(A, B, String.class);
   System.out.println("Joined Array" +joined);

For more info on Arrays comparison:

https://www.geeksforgeeks.org/java-util-arrays-equals-java-examples/