Java:比较两个字符串数组并删除两个数组中存在的元素 [英] Java: Comparing two string arrays and removing elements that exist in both arrays

查看:90
本文介绍了Java:比较两个字符串数组并删除两个数组中存在的元素的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这主要是一个性能问题.我有一个字符串数组 AllUids 中存在的所有用户的主列表.我还有一个字符串数组 EndUids 中存在的所有结束日期用户的列表.

This is mainly a performance questions. I have a master list of all users existing in a String array AllUids. I also have a list of all end dated users existing in a String array EndUids.

我在 Java 中工作,我的目标是从主列表 AllUids 中删除存在于结束日期数组中的所有用户.我知道 PHP 有一个名为 array_diff 的函数.

I am working in Java and my goal is to remove any users that exist in the end dated array from the master list AllUids. I know PHP has a function called array_diff.

我很好奇 Java 是否有任何东西可以比较两个数组并删除两者中相似的元素.我的目标是这里的性能,这就是我询问内置函数的原因.我不想添加任何特殊的包.

I was curious if Java has anything that will compare two arrays and remove elements that are similar in both. My objective is performance here which is why I asked about a built in function. I do not want to add any special packages.

我想写一个递归函数,但它似乎效率低下.两个列表中都有成千上万的用户.为了存在于结束日期列表中,您必须存在于 AllUids 列表中,即直到被移除.

I thought about writing a recursive function but it just seems like it will be inefficient. There are thousands of users in both lists. In order to exist in the end dated list, you must exist in the AllUids list, that is until removed.

示例:

String[] AllUids = {"Joe", "Tom", "Dan", "Bill", "Hector", "Ron"};

String[] EndUids = {"Dan", "Hector", "Ron"};

我正在寻找的功能:

String[] ActiveUids = AllUids.RemoveSimilar(EndUids);

ActiveUids 看起来像这样:

ActiveUids would look like this:

{"Joe", "Tom", "Bill"}

谢谢大家,显然我可以想出循环等,但我不相信它会有效.这是每天都会在生产机器上运行的东西.

Thank you all, Obviously I can come up with loops and such but I am not confident that it will be efficient. This is something that will run on production machines everyday.

推荐答案

Commons Collections 有一个类称为 CollectionUtils 和静态名为 removeAll 的方法接受一个初始列表和一个要从该列表中删除的事物列表:

Commons Collections has a class called CollectionUtils and a static method called removeAll which takes an initial list and a list of thing to remove from that list:

Collection removeAll(Collection collection,
                     Collection remove)

如果您使用用户列表而不是数组,那应该可以满足您的需求.您可以使用 Arrays.asList() 非常轻松地将数组转换为列表,因此...

That should do what you want provided you use lists of users rather than arrays. You can convert your array into a list very easily with Arrays.asList() so...

Collection ActiveUids = CollectionUtils.removeAll(Arrays.asList(AllUids), 
                                                  Arrays.asList(EndUids))

我还对 Commons Collections 进行了一些挖掘,并在 Commons Collections 中使用 ListUtils 找到了以下解决方案:

List diff = ListUtils.subtract(Arrays.asList(AllUids), Arrays.asList(EndUids));

非常整洁...

这篇关于Java:比较两个字符串数组并删除两个数组中存在的元素的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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