在删除一个ArrayList中存在的另一个数组列表中的所有对象 [英] Remove all objects in an arraylist that exist in another arraylist

查看:120
本文介绍了在删除一个ArrayList中存在的另一个数组列表中的所有对象的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想从两个文件读取,并将它们存储在两个单独的ArrayLists。该文件包含的话这是单独一行或逗号分隔的多个单词。
我阅读下列code(不完整)的每个文件:

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;

我现在需要阅读的两个文件,​​并从第一个文件的所有单词也存在于第二个文件(有在文件中一些重复的字)。我曾试图与for循环和其他类似的东西,但没有奏效,因此任何帮助将不胜AP preciated!

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!

奖金的问题:我还需要找出多少副本中有两个文件 - 我加入这两个的ArrayList到HashSet,然后从两个的ArrayList的组合大小减去集的大小做到了这一点 - 这是一个很好的解决方案,或可以做的更好。

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?

推荐答案

您可以使用的removeAll 方法,从另一个列表中删除一个列表中的项目。

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

要获得你可以使用的retainAll 方法,虽然与设定你的方法也不错(可能更有效)

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

这篇关于在删除一个ArrayList中存在的另一个数组列表中的所有对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆