简体   繁体   中英

Compare words in two arrayList<String> java

I've got two ArrayList of String and i want to count words that are in both of them.

Each ArrayList contains keyphrases, for example strings of few words like:

un'altra recessione

strada lunga

presidente barack obama

[...]

I tried with this two methods but i get a NullPointerException

 public boolean containsKeyword(String testKeyword, ArrayList<String> list) 
{ return list.contains(testKeyword);
}

public int compareKeywords(Quotidiano quotidiano){
    int sameKeywords=0;
    for(int i=0; i<this.Keywords.size(); i++){
            if(this.containsKeyword(this.getKeyword(i), quotidiano.Keywords))
             sameKeywords++;
          }

    return sameKeywords;
}

Thanks a lot for answers!


[EDIT]

It worked using intersection, thank you! But it would be better if it compares single words.

For example, if i have keyphrases

"spread of italy",

"spread under 300",

I think intersection is null, instead i would like "spread" returned. How can I do it?

Use Apache ListUtils Intersection

public static java.util.List intersection(java.util.List list1,
                                      java.util.List list2)

PS: This throws java.lang.NullPointerException - if either list is null

You should check for null whenever you are getting an input from unknown source. You should not count that the input is OK.

public boolean containsKeyword(String testKeyword, ArrayList<String> list) 
{ 
    return (list != null) ? list.contains(testKeyword) : false;
}

public int compareKeywords(Quotidiano quotidiano){
    if(quotidiano == null || this.Keywords == null) return 0;
    int sameKeywords=0;
     for(int i=0; i<this.Keywords.size(); i++){
        if(this.containsKeyword(this.getKeyword(i), quotidiano.Keywords))
         sameKeywords++;
    }

    return sameKeywords;
}

checking this.Keyword is optional as I assume that's your code and you are aware it should always be different then null.

NullPointerException occurs when you are using member of any object and that object is not yet initialized. Make sure both the lists are initialized and are not null.

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