2

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?

2
  • What if s1 = {"a", "b"} and s2 = {"c", "d"}, what would your difference array be? {"a", "b"} or {"a", "b", "c", "d"}? Commented Feb 8, 2010 at 10:23
  • Duplicate: stackoverflow.com/questions/2207673/… Commented Feb 8, 2010 at 10:44

4 Answers 4

7

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.

Sign up to request clarification or add additional context in comments.

Comments

4

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.

3 Comments

Added this just for the sake of providing an implementation. If I had this problem myself I would go with Bart K.'s solution.
You cannot modify a list, which is created with Arrays.asList(...).
@jarnbjo True, changed the answer.
0

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.

Comments

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.