Thursday, August 4, 2011

Set Operations in Java

What is a Set


Mathematically, a set is just a collection of objects, for example
let set=["apple","orange","banana"]

For a simple set, the order of the element is not important.

You can add element to a set.
set.add("strawberry") is ["apple","orange","banana". "strawberry"]

You can remove element from a set
set.remove("orange") is ["apple","banana","strawberry"]

You can ask whether a set contains a certain element.
set.contains("banana") is true

The following is a simple example.



Compile and run :
javac SetDemo.java
java SetDemo

[banana, orange, apple]
[banana, orange, apple, strawberry]
[banana, apple, strawberry]
apple in the set=true
orange in the set=false

Set Operations : union, intersection, difference, subset

  • Union: set1.addAll(set2);
  • Intersection: set1.retainAll(set2);
  • Difference: set1.removeAll(set2);
  • subset test: set1.containsAll(set2);

Sample :
Suppose a person has three friends :
friends = ["Helen","Mary","John"];

Suppose he has three classmates :
classmates = ["John","Peter","Mary"];

"Peter" belongs to classmates but not friends, because he treats "Peter" as enemy.

Then,
intersection = set of people who is a friend as well as a classmate
             = ["John","Mary"];

union = set of people who is either a friend or a classmate
      = ["John", "Mary", "Peter", "Helen"];


subset test :
  friends.containAll(classmates) would return false, 
  because not all classmates are friends.
  That is, classmates is not a subset of friends

The following is the program that demonstrated the above operations.


Result

javac SetOperation.java
java SetOperation

friends=[Mary, John, Helen]
classmates=[Mary, Peter, John]
intersection=[Mary, John]
union=[Mary, Peter, John, Helen]
'classmates' is a subset of 'friends' : false

2 comments: