开发者

Find String Array Difference in Java

I created two array variables: s1 and s2 s1 contains {ram,raju,seetha} s2 contains {ram}

I want to subtract the two arrays as s开发者_开发百科ets, in order to get the following result:

raju seetha

How can I do this?


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.


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.


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.


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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜