Remove all objects in an arraylist that exist in another arraylist

前端 未结 4 1471
梦谈多话
梦谈多话 2020-12-17 07:25

I\'m trying to read in from two files and store them in two separate arraylists. The files consist of words which are either alone on a line or multiple words separated by c

相关标签:
4条回答
  • 2020-12-17 08:07

    First you need to override equal method in your custom class and define the matching criteria of removing list

    public class CustomClass{
    
     @Override
        public boolean equals(Object obj) {
    
            try {
                CustomClass licenceDetail  = (CustomClass) obj;
                return name.equals(licenceDetail.getName());
            }
            catch (Exception e)
            {
                return false;
            }
    
        }
    }
    

    Second you call the removeAll() method

    list1.removeAll(list2);

    0 讨论(0)
  • 2020-12-17 08:11

    The collection facility has a convenient method for this purpose:

    list1.removeAll(list2);
    
    0 讨论(0)
  • 2020-12-17 08:17

    As others have mentioned, use the Collection.removeAll method if you wish to remove all elements that exist in one Collection from the Collection you are invoking removeall on.

    As for your bonus question, I'm a huge fan of Guava's Sets class. I would suggest the use of Sets.intersection as follows:

    Sets.intersection(wordSetFromFile1, wordSetFromFile2).size();
    

    Assuming you created a Set of words from both files, you can determine how many distinct words they have in common with that one liner.

    0 讨论(0)
  • 2020-12-17 08:22

    You can use the removeAll method to remove the items of one list from another list.

    To obtain the duplicates you can use the retainAll method, though your approach with the set is also good (and probably more efficient)

    0 讨论(0)
提交回复
热议问题