Sort Lexicographical Order of Substrings in Java


The challenge

Given two arrays of strings a1 and a2 return a sorted array r in lexicographical order of the strings of a1 which are substrings of strings of a2.

Example 1:

a1 = ["arp", "live", "strong"]

a2 = ["lively", "alive", "harp", "sharp", "armstrong"]

returns ["arp", "live", "strong"]

Example 2:

a1 = ["tarp", "mice", "bull"]

a2 = ["lively", "alive", "harp", "sharp", "armstrong"]

returns []

The solution in Java code

Option 1:

import java.util.ArrayList;
import java.util.List;

public class WhichAreIn {
    public static String[] inArray(String[] array1, String[] array2) {
        List<String> in = new ArrayList<>();
        for (String a : array1)
            for (String b : array2) if (b.contains(a)) in.add(a);
        return in.stream().distinct().sorted().toArray(String[]::new);
    }
}

Option 2:

import java.util.stream.Stream;

public class WhichAreIn { 
  public static String[] inArray(String[] array1, String[] array2) {
    return Stream.of(array1)
      .filter(x -> Stream.of(array2).anyMatch(y -> y.contains(x)))
      .distinct()
      .sorted()
      .toArray(String[]::new);
  }
}

Option 3:

import java.util.*;

public class WhichAreIn { 
  public static String[] inArray(String[] array1, String[] array2) {
    List<String> result = new ArrayList<String>();
      for(int i=0; i<array1.length; i++){
         for(int j=0; j<array2.length; j++ ){
            if(array2[j].indexOf(array1[i]) >= 0){
              result.add(array1[i]);
              j =array2.length;
            }
          }
      }
    Collections.sort(result);
    return result.toArray(new String[result.size()]);
  }
}

Test cases to validate our solution

import org.junit.jupiter.api.Test;
import static org.junit.jupiter.api.Assertions.*;

public class WhichAreInTest {
    @Test
    public void test1() {
        String[] a = new String[]{ "arp", "live", "strong" };
        String[] b = new String[] { "lively", "alive", "harp", "sharp", "armstrong" };
        String[] r = new String[] { "arp", "live", "strong" };
        assertArrayEquals(r, WhichAreIn.inArray(a, b));
    }
    @Test
    public void test2() {
        String[] a = new String[]{ "cod", "code", "wars", "ewar", "pillow", "bed", "phht" };
        String[] b = new String[] { "lively", "alive", "harp", "sharp", "armstrong", "codewars", "cod", "code" };
        String[] r = new String[] { "cod", "code", "ewar", "wars" };
        assertArrayEquals(r, WhichAreIn.inArray(a, b));
    }
}