Search code examples
javaarraylistcollections

How to compare two arraylist containing objects with shared properties?


How to compare two arraylist containing objects with shared properties?

For example, I have a pojo class Abc:

Class Abc {
String dataString ;
int rowNum;
......
}

Abc list1 contains - 2000 records & more sometimes
Abc list2 contains - 60 records & more sometimes

I want to compare list1 dataString to list2 datastring and return rownum if list1.dataString Notequals list2.dataString

I need rowNumber from List1 if data string DOESN'T matches. List2 Rownum can be ignored.


Solution

  • In high-level terms, your code should:

    • iterate over list1
    • for each element check whether its data string appears somewhere in list2
    • if so, include the row number of the list1 element in the result

    To make the code fast, in the second step the set of list2 data strings can be precomputed. Still in high-level terms, the code is:

    List<int> filtered(List<Abc> list1, List<Abc> list2) {
        var dataStrings = setOf(list2.map(x -> x.dataString));
    
        var abcs = list1.filter(x -> dataStrings.contains(x.dataString));
    
        return abcs.map(x -> x.rowNum);
    }
    

    In standard Java, the code looks more bloated, of course:

    List<int> filtered(List<Abc> list1, List<Abc> list2) {
        Set<String> dataStrings = list2.stream()
            .map(x -> x.dataString))
            .collect(Collectors.toSet());
    
        return list1.stream()
            .filter(x -> dataStrings.contains(x.dataString))
            .map(x -> x.rowNum)
            .collect(Collectors.toList());
    }