简体   繁体   中英

How to check if elements of 2 lists are contained within the other?

I'd like to verify if each element contained in a List<String> is contained in any element of a 2nd list.

Example:

[hotel, appartment]
[hotel, appart]

Analye:

hotel      <> hotel  -> OK  (100% match)
appartment <> hotel  -> NOK 
appartment <> appart -> OK  ("appartment" is not contained in "appart", but the other way around)

whereas <> reads: either of both is included in the other string.

How could this be done best, especially from point of performance? Is there already a apache commons or guava function handling these cases?

is that what you are looking for? i did not run this code, just wrote it on notepad...

for(int a=0;a<listA.size();a++){
    for(int b=0;b<listB.size();b++){
        if(listA.get(a).equals(listB.get(b))){
            System.out.println(listA.get(a) + "<>" + listB.get(b) + " -> OK  (100% match)");
        }else{
            //if not match, check if contained
            if(listA.get(a).indexOf(listB.get(b))!=-1 || listB.get(b).indexOf(listA.get(a))!=-1){
                System.out.println(listA.get(a) + "<>" + listB.get(b) + " -> OK  ("appartment" is not contained in "appart", but the other way around)");
            }else{
                System.out.println(listA.get(a) + "<>" + listB.get(b) + " -> NOK ");
            }
        }
    }//for list B
}//for list A

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM