1

I am trying to save all common words from arr1 and arr2 and then store to arr3.

String[] arr1 = {"pEace", "happiness", "Gives", "So", "aaa"};
String[] arr2 = {"pEace", "HappiNess", "joy", "give", "AAA", "enjoy", "learN"};

int k = 0;
String[] arr3 = new String[0];
for (int i = 0; i < arr1.length; i++) {
    for (int j = 0; j < arr2.length; j++) {
        if (arr1[i].equalsIgnoreCase(arr2[j])) {
            System.out.println(arr1[i]);
            arr3[k] = arr1[i];
            k++;
        }
    }
}
System.out.println(Arrays.toString(arr3));

2 Answers2

2

The init size of arr3 is 0

String[] arr3 = new String[0];

You should init with size is total length of arr1 and arr2 or use ArrayList. On that example are 12

Basil Bourque
  • 303,325
  • 100
  • 852
  • 1,154
Thieu
  • 44
  • 3
  • 1
    Number of common elements will not exceed length of smaller array. `String[] arr3 = new String[Math.min(arr1.length, arr2.length)];` should do it. – the Hutt Apr 02 '21 at 04:39
  • Thank you for help but still I am not getting the right result. I know the result should be [ pEace, happiness, aaa ] these 3 strings I am trying to save on arr3, but my resulte is come up like this [null, null, null, null, null, null] – ArianGorani Apr 02 '21 at 13:47
  • You are missing import java.util.Arrays; import statement on top of the class. – Thieu Apr 03 '21 at 03:14
0

You can convert these arrays to collections and then use the retainAll method. It works differently in different collections.

Try it online!

// Convert arrays to collections
String[] arr1 = {"pEace", "happiness", "Gives", "So", "aaa", "learn"};
String[] arr2 = {"pEace", "HappiNess", "joy", "give", "AAA", "learN"};

Collection<String> coll1 = Arrays.asList(arr1);
Collection<String> coll2 = Arrays.asList(arr2);
// ArrayList
ArrayList<String> list1 = new ArrayList<>();
ArrayList<String> list2 = new ArrayList<>();

list1.addAll(coll1);
list2.addAll(coll2);

list2.retainAll(list1);

System.out.println(list2); // [pEace]
// TreeSet
TreeSet<String> set1 = new TreeSet<>(String.CASE_INSENSITIVE_ORDER);
TreeSet<String> set2 = new TreeSet<>(String.CASE_INSENSITIVE_ORDER);

set1.addAll(coll1);
set2.addAll(coll2);

set2.retainAll(set1);

System.out.println(set2); // [AAA, HappiNess, learN, pEace]

See also: Is it possible that TreeSet equals HashSet but not HashSet equals TreeSet