2

I am relativly new to Java and I am wondering if there is a method like LINQs "Except" in C# to get the different items of two sets.

I looked at CollectionUtils from apache common, Collections and Collections2 from guava but found no such method.

Btw: I am using Java 7 not Java 8.

Luiggi Mendoza
  • 85,076
  • 16
  • 154
  • 332
leozilla
  • 1,296
  • 2
  • 19
  • 29
  • Are you asking on Java or C#? – Luiggi Mendoza Sep 02 '14 at 04:41
  • Java has a Set interface which would likely have what you're looking for. If you're simply looking under the Collection area, you might not find it. If you insist on using Collections, you should look at the guava libraries – Joe Phillips Sep 02 '14 at 04:44
  • 1
    @LuiggiMendoza It is quite clear that he is working in Java. – cdhowie Sep 02 '14 at 04:45
  • 1
    I think i found was i was looking for it is right on the Sets util class, i was somehow not seeing it in the first place. The method is called "Sets.difference". – leozilla Sep 02 '14 at 04:50
  • @Rajacsp the dupe you pointed out is old and of lower quality. It does not for example state which language the question is about. – Peter Lamberg Sep 02 '14 at 05:00

3 Answers3

3

I have used Guava Sets.difference.

The parameters are sets and not general collections, but a handy way to create sets from any collection (with unique items) is Guava ImmutableSet.copyOf(Iterable).

Loxley
  • 1,781
  • 17
  • 20
Peter Lamberg
  • 8,151
  • 3
  • 55
  • 69
2

Suppose you have:

...
Set<int> s1 = new HashSet<Integer>();
Set<int> s2 = new HashSet<Integer>();
...

You can try this

s2.removeAll(s1);

See the doc for Set#removeAll

NOTE: This will modify the set, but you can have a copy of it.

JosEduSol
  • 5,268
  • 3
  • 23
  • 31
0

You can Try this

collection2.removeAll(collection1);

Although this will mutate collection2, so create a copy if you need to preserve it.

JavaBeigner
  • 608
  • 9
  • 28
Diptesh
  • 46
  • 4