Bsic Operation on Set part II

Adding elements to a Set:The add()method returns true if the set does not contain the specified element, and returns false if the set already contains the specified element:

1
2
3
4
5
6
7
8
9
10
11
Set<String> names = new HashSet<>();
names.add("Tom");
names.add("Mary");
if (names.add("Peter")) {
    System.out.println("Peter is added to the set");
}
if (!names.add("Tom")) {
    System.out.println("Tom is already added to the set");
}

Output:

1
2
Peter is added to the set
Tom is already added to the set

The Set can contain a null element:

1
names.add(null);

Removing an element from a Set:The remove() method removes the specified element from the set if it is present (the method returns true, or false otherwise):

1
2
3
if (names.remove("Mary")) {
    System.out.println("Marry is removed");
}

Note that the objects in the Set should implement the equals() and hashCode() methods correctly so the Set can find and remove the objects. Check if a Set is empty:The isEmpty() method returns true if the set contains no elements, otherwise returns false:

1
2
3
4
5
if (names.isEmpty()) {
    System.out.println("The set is empty");
} else {
    System.out.println("The set is not empty");
}

Remove all elements from a Set:The clear() method removes all elements from the set. The set will be empty afterward:

1
2
3
4
5
names.clear();
if (names.isEmpty()) {
    System.out.println("The set is empty");
}

Get total number of elements in a Set:The size() method returns the number of elements contained in the set:

1
2
3
4
5
6
7
Set<String> names = new HashSet<>();
names.add("Tom");
names.add("Mary");
names.add("Peter");
names.add("Alice");
System.out.printf("The set has %d elements", names.size());

Output:

1
The set has 4 elements

Note that the Set interface does not provide any API for retrieving a specific element due to its nature of unordered. Except the TreeSet implementation allows retrieving the first and the last elements.

 Iterating over elements in a Set

Using an iterator:

1
2
3
4
5
6
7
8
9
10
11
12
13
Set<String> names = new HashSet<>();
names.add("Tom");
names.add("Mary");
names.add("Peter");
names.add("Alice");
Iterator<String> iterator = names.iterator();
while (iterator.hasNext()) {
    String name = iterator.next();
    System.out.println(name);
}  

Output:

1
2
3
4
Tom
Alice
Peter
Mary   

Using the enhanced for loop:

1
2
3
for (String name : names) {
    System.out.println(name);
}

Using the forEach() method with Lambda expression in Java 8:

1
names.forEach(System.out::println);

 

Searching for an element in a Set

The contains(Object) method returns true if the set contains the specified element, or return false otherwise. For example:

1
2
3
4
5
6
7
8
9
Set<String> names = new HashSet<>();
names.add("Tom");
names.add("Mary");
names.add("Peter");
names.add("Alice");
if (names.contains("Mary")) {
    System.out.println("Found Mary");
}

Note that if the set contains custom objects of your own type, e.g. Student or Employee, the object should implement theequals() and hashCode() methods correctly so the Set can find the objects.

Performing Bulk Operations between two Sets

We can perform some mathematic-like operations between two sets such as subset, union, intersection and set difference. Suppose that we have two sets s1 and s2.Subset operation:

  • s1.containsAll(s2) returns true if s2 is a subset of s1 (s2 is a subset of s1 if s1 contains all of the elements in s2).

Example:

1
2
3
4
5
6
Set<Integer> s1 = new HashSet<>(Arrays.asList(20, 56, 89, 31, 8, 5));
Set<Integer> s2 = new HashSet<>(Arrays.asList(8, 89));
if (s1.containsAll(s2)) {
    System.out.println("s2 is a subset of s1");
}

Output:

1
s2 is a subset of s1

Union operation:

  • s1.addAll(s2) — transforms s1 into the union of s1 and s2. (The union of two sets is the set containing all of the elements contained in either set.)

Example:

1
2
3
4
5
6
7
8
Set<Integer> s1 = new HashSet<>(Arrays.asList(1, 3, 5, 7, 9));
Set<Integer> s2 = new HashSet<>(Arrays.asList(2, 4, 6, 8));
System.out.println("s1 before union: " + s1);
s1.addAll(s2);
System.out.println("s1 after union: " + s1);

Output:

1
2
s1 before union: [1, 3, 5, 7, 9]
s1 after union: [1, 2, 3, 4, 5, 6, 7, 8, 9]

 Intersection operation:

  • s1.retainAll(s2) — transforms s1 into the intersection of s1 and s2. (The intersection of two sets is the set containing only the elements common to both sets.)

Example:

1
2
3
4
5
6
7
8
Set<Integer> s1 = new HashSet<>(Arrays.asList(1, 2, 3, 4, 5, 7, 9));
Set<Integer> s2 = new HashSet<>(Arrays.asList(2, 4, 6, 8));
System.out.println("s1 before intersection: " + s1);
s1.retainAll(s2);
System.out.println("s1 after intersection: " + s1);

Output:

1
2
s1 before intersection: [1, 2, 3, 4, 5, 7, 9]
s1 after intersection: [2, 4]

Set difference operation:

  • s1.removeAll(s2) — transforms s1 into the (asymmetric) set difference of s1 and s2. (For example, the set difference of s1 minus s2 is the set containing all of the elements found in s1 but not in s2.)

Example:

1
2
3
4
5
6
7
8
Set<Integer> s1 = new HashSet<>(Arrays.asList(1, 2, 3, 4, 5, 7, 9));
Set<Integer> s2 = new HashSet<>(Arrays.asList(2, 4, 6, 8));
System.out.println("s1 before difference: " + s1);
s1.removeAll(s2);
    
System.out.println("s1 after difference: " + s1);

Output:

1
2
s1 before difference: [1, 2, 3, 4, 5, 7, 9]
s1 after difference: [1, 3, 5, 7, 9]

 

Concurrent Sets

All three implementations HashSet, LinkedHashSet and TreeSet are not synchronized. So if you use them in concurrent context (multi-threads), you have to synchronize them externally using Collections.synchronizedSet() static method. For example:

1
Set<Integer> numbers = Collections.synchronizedSet(new HashSet<Integer>());

The returned set is synchronized (thread-safe). And remember you must manually synchronize on the returned set when iterating over it:

1
2
3
4
5
6
7
8
synchronized (numbers) {
    Iterator<Integer> iterator = numbers.iterator();
    while (iterator.hasNext()) {
        Integer number = iterator.next();
        System.out.println(number);
    }
Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

Blog at WordPress.com.

Up ↑

%d bloggers like this: