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?
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?
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.