查找 Java 中字符串数组的差异

发布于 2024-08-20 10:44:17 字数 129 浏览 7 评论 0原文

我创建了两个数组变量: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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(4

飘然心甜 2024-08-27 10:44:17

如果数组中的元素是唯一的,您可以创建一个 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.

长安忆 2024-08-27 10:44:17

您可以通过循环遍历项目来获得差异:

String[] s1 = {"ram", "raju", "seetha"};
String[] s2 = {"ram"};
List<String> s1List = new ArrayList(Arrays.asList(s1));
for (String s : s2) {
  if (s1List.contains(s)) {
    s1List.remove(s);
  }
  else {
    s1List.add(s);
  }
}

s1List 包含两个数组之间的差异。

You could get the difference by looping through the items:

String[] s1 = {"ram", "raju", "seetha"};
String[] s2 = {"ram"};
List<String> s1List = new ArrayList(Arrays.asList(s1));
for (String s : s2) {
  if (s1List.contains(s)) {
    s1List.remove(s);
  }
  else {
    s1List.add(s);
  }
}

s1List contains the different between the two arrays.

甜嗑 2024-08-27 10:44:17

要自己实现这一点(例如,如果这是家庭作业,并且您还没有学习 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.

一袭水袖舞倾城 2024-08-27 10:44:17
public ArrayList getUnique( ArrayList original, ArrayList subset ){
        ArrayList u = new ArrayList();
        Collection<ArrayList> o = original;
        Collection<ArrayList> s = subset;

        o.removeAll(s);
        u.addAll(o);

        return u;
}

您可以从上面的代码中减少几行,但为了清楚起见,我保留了它。

public ArrayList getUnique( ArrayList original, ArrayList subset ){
        ArrayList u = new ArrayList();
        Collection<ArrayList> o = original;
        Collection<ArrayList> s = subset;

        o.removeAll(s);
        u.addAll(o);

        return u;
}

You can reduce a few lines from above code but I have kept it for clarity.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文