views:

472

answers:

3

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?

+5  A: 

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.

Bart Kiers
+2  A: 

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.

Wesho
Added this just for the sake of providing an implementation. If I had this problem myself I would go with Bart K.'s solution.
Wesho
You cannot modify a list, which is created with `Arrays.asList(...)`.
jarnbjo
@jarnbjo True, changed the answer.
Wesho
+1  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.

Fabian Steeg