Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
243 views
in Technique[技术] by (71.8m points)

java - Remove all objects in an arraylist that exist in another arraylist

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 commas. I read each file with the following code (not complete):

ArrayList<String> temp = new ArrayList<>();

FileInputStream fis;
fis = new FileInputStream(fileName);

Scanner scan = new Scanner(fis);

while (scan.hasNextLine()) {
    Scanner input = new Scanner(scan.nextLine());
    input.useDelimiter(",");
    while (scan.hasNext()) {
        String md5 = scan.next();
        temp.add(md5);
    }
}
scan.close();    

return temp;

I now need to read two files in and remove all words from the first file which also exist in the second file (there are some duplicate words in the files). I have tried with for-loops and other such stuff, but nothing has worked so any help would be greatly appreciated!

Bonus question: I also need to find out how many duplicates there are in the two files - I've done this by adding both arraylists to a HashSet and then subtracting the size of the set from the combined size of the two arraylists - is this a good solution, or could it be done better?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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)


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...