Search code examples
javasortingarraylistcomparison

Compare two String Arraylists complex


I have Two ArrayLists with String values stored in them. The lists can be: of different size, have same values per list and different non matching strings.

Example:

List 1: "a","b","b","c","e","a","e","f","g";

List 2: "a","a","b","c","a","e","a","d","f","e","e","g";

The result I want to get is the matching values in the order of List 1 in comparison to List 2. So the result from the example would be:

Result:

[String] [pos L1] [pos L2]

["a"] [0] [0]

["b"] [1] [2]

["c"] [3] [3]

["e"] [4] [5]

["a"] [5] [6]

["e"] [6] [9]

["g"] [8] [11]

Solution

  • Perform two nested loops and start iterating in the second loop from the index you stopped in the last iteration of your inner loop:

    public static List<String> algo(List<String> l1, List<String> l2) {
            List<String> result = new ArrayList<>();
    
            int lastIndexFound = 0;
    
            for(int i = 0; i < l1.size(); i++) {
                for(int j = lastIndexFound; j < l2.size(); j++) {
                    String list1element = l1.get(i);
                    String list2element = l2.get(j);
                    if(list1element.equals(list2element)) {
                        result.add(list1element);
                        lastIndexFound = j + 1;
                        break;
                    }
                }
            }
    
            return result;
        }
    

    For testing :

    List<String> list = Lists.newArrayList("a","b","b","c","e","a","e","f","g");
    List<String> list2 = Lists.newArrayList("a","a","b","c","a","e","a","d","f","e","e","g");
    
    algo(list, list2).forEach(System.out::println);
    

    This outputs :

    a
    b
    c
    e
    a
    e
    g