查找 Java 中字符串数组的差异
我创建了两个数组变量:s1 和 s2 s1 包含 {ram,raju,seetha} s2 包含 {ram}
我想将两个数组作为集合相减,以获得以下结果:
raju seetha
我该怎么做?
I created two array variables: s1 and s2
s1 contains {ram,raju,seetha}
s2 contains {ram}
I want to subtract the two arrays as sets, in order to get the following result:
raju
seetha
How can I do this?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
如果数组中的元素是唯一的,您可以创建一个 java.util.Set 并执行 removeAl(...)。如果它们不是唯一的,请使用 java.util .List 代替。
If the elements in your array are unique, you could create a java.util.Set and do a removeAl(...). If they're not unique, go for a java.util.List instead.
您可以通过循环遍历项目来获得差异:
s1List
包含两个数组之间的差异。You could get the difference by looping through the items:
s1List
contains the different between the two arrays.要自己实现这一点(例如,如果这是家庭作业,并且您还没有学习 Java 集合 API),您可以像这样处理它:对于第一个数组中的每个元素,如果该元素不包含在结果中,则将该元素添加到结果中另一个数组。现实世界的解决方案是使用集合,如 Bart 所描述< /a>.
To implement this yourself (e.g. if this is homework and you did not learn about the Java collections API yet) you could approach it like this: for every element in the first array, add the element to the result, if it is not contained in the other array. The real-world solution would be to use sets, as described by Bart.
您可以从上面的代码中减少几行,但为了清楚起见,我保留了它。
You can reduce a few lines from above code but I have kept it for clarity.