Home » Core Java » util » Set » Java Set Example

About Xenofon Dimitroulis

Xenofon Dimitroulis
Xenofon has graduated from the Department of Informatics at Athens University of Economic and Business. His studies were focused in the area of Information Management, as well as Computer Systems and Networks. He has successfully developed a series of projects varying form simple desktop, web and mobile applications, scaling to more complex which included AI algorithm implementations and Multithreaded Distributed Systems.

Java Set Example

In this example we will demonstrate the use of the interface Set, which is part of the Java Collections Framework. It extends the interface Collection so that all elements contained have no dublicates and only one null element may appear.

There are several classes implementing the interface, such as AbstractSet, EnumSet, HashSet, LinkedHashSet, TreeSet and ConcurrentSkipListSet. The classes HashSet and TreeSet are the most commonly used.

HashSet implements the interface using a hash table. It offers high performance for the basic methods such as add, remove, contains and size, however the ordering of the elements cannot be tracked and possibly it could change at anytime during execution.

TreeSet uses a TreeMap to store the elements, which keeps them sorted by their natural order or by the comparator that we prefer to use.

1. How to create a Set:

Lets have a look at the HashSet class constructors:

  • HashSet(): Constructs a new, empty set.
  • HashSet(Collection): Constructs a new set, which contains the elements of the given collection.
  • HashSet(int initialCapacity): Constructs a new, empty set, with the specified initial capacity.
  • HashSet(int initialCapacity, float loadFactor): Constructs a new, empty set, with the specified initial capacity and load factor.

2. Common Methods:

  • add(Object): Adds a new element, if it does not exist already.
  • addAll(Collection): Adds all the elements of the given collection, if the do not exist already. If the given collection is also a set, then the execution of the method results in the union of the two sets.
  • contains(Object): Returns true if the elements given exists in the set.
  • containsAll(Collection): Returns true if all the elements in the given collection exist in the set. In case the given collection is a set, the method return true if it is a subset of this set.
  • equals(Object): Returns true if the given object that is compared with this set is also a set, both of them contain the same number of elements and every element of the given set is contained in this set.
  • size(): Returns the number of the elements in the set.
  • remove(Object): Removes the specified elements from the set.
  • removeAll(Collection): Removes from the set all the elements that the collection contains.
  • clear(): Removes all the elements from the set, resulting in an empty set.
  • isEmpty(): Returns true if the set has no elements.
  • hashCode(): Returns the hash code value of this set. The hash code of a set is the sum of the hash codes of the elements contained in the set.
  • toArray(): Return an array containing all the elements of this set.

3. Examples of using Set in Java:

Let’s see how you can use HashSet in practice:

SetExample.java:

       
package com.javacodegeeks.core.set;

import java.util.*;

public class SetExample {

    public static void main(String args[]) {

        // We create a new, empty set
        Set mySet1 = new HashSet();
        // We add a few elements
        mySet1.add("A");
        mySet1.add("C");
        mySet1.add("A");
        mySet1.add("B");
        // Print the elements of the Set
        System.out.println("mySet1: " + mySet1);

        // Create a list and add some elements
        List list = new ArrayList();
        list.add("A");
        list.add("C");
        list.add("A");
        list.add("A");
        list.add("B");
        list.add("C");
        // Now create the set using the appropriate constructor
        Set mySet2 = new HashSet(list);
        // Print the elements of the list an the the set
        System.out.println("list: " + list);
        System.out.println("mySet2: " + mySet2);

        // Compare the two sets
        System.out.println("MySet1 matches mySet2: " + mySet1.equals(mySet2));

        // Now we will remove one element from mySet2 and compare again
        mySet2.remove("A");
        System.out.println("mySet2: " + mySet2);
        System.out.println("MySet1 matches mySet2: " + mySet1.equals(mySet2));

        // Lets check if our sets contain all the elements of the list
        System.out.println("MySet1 contains all the elements: " + mySet1.containsAll(list));
        System.out.println("MySet2 contains all the elements: " + mySet2.containsAll(list));

        // Use of Iterator in Set
        Iterator iterator = mySet1.iterator();
        while (iterator.hasNext()) {
            System.out.println("Iterator loop: " + iterator.next());
        }

        // Use of for-each in Set
        for (String str : mySet1) {
            System.out.println("for-each loop: " + str);
        }

        // Clearing all the elements
        mySet1.clear();
        System.out.println("mySet1 is Empty: " + mySet1.isEmpty());

        // Checking the number of elements
        System.out.println("mySet1 has: " + mySet1.size() + " Elements");
        System.out.println("mySet2 has: " + mySet2.size() + " Elements");

        // Creating an Array with the contents of the set
        String[] array = mySet2.toArray(new String[mySet2.size()]);
        System.out.println("The array:" + Arrays.toString(array));
    }
}

Output:

mySet1: [A, B, C]
list: [A, C, A, A, B, C]
mySet2: [A, B, C]
MySet1 matches mySet2: true
mySet2: [B, C]
MySet1 matches mySet2: false
MySet1 contains all the elements: true
MySet2 contains all the elements: false
Iterator loop: A
Iterator loop: B
Iterator loop: C
for-each loop: A
for-each loop: B
for-each loop: C
mySet1 is Empty: true
mySet1 has: 0 Elements
mySet2 has: 2 Elements
The array:[B, C]

 

This was a Java Set Example.

Download the Eclipse project of this example: JavaSetExample.zip

(No Ratings Yet)
Start the discussion Views Tweet it!

Do you want to know how to develop your skillset to become a Java Rockstar?

Subscribe to our newsletter to start Rocking right now!

To get you started we give you our best selling eBooks for FREE!

 

1. JPA Mini Book

2. JVM Troubleshooting Guide

3. JUnit Tutorial for Unit Testing

4. Java Annotations Tutorial

5. Java Interview Questions

6. Spring Interview Questions

7. Android UI Design

 

and many more ....

 

Receive Java & Developer job alerts in your Area

 

Leave a Reply

avatar
  Subscribe  
Notify of