Provide Best Programming Tutorials

Set In Java

Introduction To Set

A set is an efficient data structure for storing and processing nonduplicate elements.

You can create a set using one of its three concrete classes:

  • HashSet
  • TreeSet
  • LinkedHashSet

The Set interface extends the Collection interface, as shown in Figure below. It does not introduce new methods or constants, but it stipulates that an instance of Set contains no duplicate elements. The concrete classes that implement Set must ensure that no duplicate elements can be added to the set. That is, no two elements e1 and e2 can be in the set such that e1.equals(e2) is true .

 

HashSet

package SetDemo;

import java.util.HashSet;
import java.util.Set;

public class SetDemo {

    public static void main(String[] args) {
        Set hashSet = new HashSet();
        String benz = "benz";
        String bmw = "bmw";
        String bmw1 = "bmw";
        String bmw2 = new String("bmw");

        System.out.println(benz.hashCode());
        System.out.println(bmw.hashCode());
        System.out.println(bmw1.hashCode());
        System.out.println(bmw2.hashCode());

        hashSet.add(benz);
        hashSet.add(bmw);
        hashSet.add(bmw1);
        hashSet.add(bmw2);

        System.out.println(hashSet);

    }
}

output

3020111
97676
97676
97676
[benz, bmw]

As you can see if the object’s hashcode is the same then set will only one “bmw” is added to thehashSet

How HashSet judge whether two elements are equal or not

HashSet using hashcode and equals methods to ensure there is no duplicate element in the set.

Add, Remove, Find and Iterate Element In Set

  • Add an element using methodadd().

  • Remove an element using methodremove().

  • Find an element using methodcontains().

Iterate set

  • using iterator
  • using for-each
package SetDemo;

import java.util.HashSet;
import java.util.Iterator;
import java.util.Set;

public class SetDemo {

    public static void main(String[] args) {
        Set<String> hashSet = new HashSet();
        String benz = "benz";
        String bmw = "bmw";
        String bmw1 = "bmw";
        String bmw2 = new String("bmw");

        System.out.println(benz.hashCode());
        System.out.println(bmw.hashCode());
        System.out.println(bmw1.hashCode());
        System.out.println(bmw2.hashCode());

        hashSet.add(benz);
        hashSet.add(bmw);
        hashSet.add(bmw1);
        hashSet.add(bmw2);

        System.out.println(hashSet);

        System.out.println(hashSet.contains("benz"));

        hashSet.remove("benz");

        System.out.println(hashSet.contains("benz"));


        System.out.println("----------Using Iterator----------");

        Iterator<String> itr = hashSet.iterator();
        while (itr.hasNext()) {
            System.out.println(itr.next());
        }

        System.out.println("----------Using foreach----------");

        for (String item : hashSet) {
            System.out.println(item);
        }
    }
}

LinkedHashSet

LinkedHashSet extends HashSet with a linked-list implementation that supports an ordering of the elements in the set. The elements in a HashSet are not ordered, but the elements in a LinkedHashSet can be retrieved in the order in which they were inserted into the set. A LinkedHashSet can be created by using one of its four constructors, as shown in Figure above These constructors are similar to the constructors for HashSet.

package SetDemo.linkedHashSetDemo;

import java.util.LinkedHashSet;
import java.util.Set;

public class LinkedHashSetDemo {


    public static void main(String[] args) {
        // Create a hash set
        Set<String> set = new LinkedHashSet<>();

        // Add strings to the set
        set.add("London");
        set.add("Paris");
        set.add("New York");
        set.add("San Francisco");
        set.add("Beijing");
        set.add("New York");

        System.out.println(set);

        // Display the elements in the hash set
        for (String element : set)
            System.out.print(element.toLowerCase() + ",");
    }
}

TreeSet

SortedSet is a subinterface of Set, which guarantees that the elements in the set are sorted. Additionally, it provides the methods first() and last() for returning the first and last elements in the set, and headSet(toElement) and tailSet(fromElement) for returning a portion of the set whose elements are less than toElement and greater than or equal to fromElement, respectively.

NavigableSet extends SortedSet to provide navigation methods lower(e), floor(e), ceiling(e), and higher(e) that return elements respectively less than, less than or equal, greater than or equal, and greater than a given element and return null if there is no such element. The pollFirst() and pollLast() methods remove and return the first and last element in the tree set, respectively.

TreeSet implements the SortedSet interface. To create a TreeSet, use a constructor, as shown in Figure above.

import java.util.HashSet;
import java.util.Set;
import java.util.TreeSet;

public class TreeSetDemo {


    public static void main(String[] args) {
        // Create a hash set
        Set<String> set = new HashSet<>();

        // Add strings to the set
        set.add("London");
        set.add("Paris");
        set.add("New York");
        set.add("San Francisco");
        set.add("Beijing");
        set.add("New York");

        TreeSet<String> treeSet = new TreeSet<>(set);
        System.out.println("Sorted tree set: " + treeSet);

        // Use the methods in SortedSet interface
        System.out.println("first(): " + treeSet.first());
        System.out.println("last(): " + treeSet.last());
        System.out.println("headSet(\"New York\"): " +
                treeSet.headSet("New York"));
        System.out.println("tailSet(\"New York\"): " +
                treeSet.tailSet("New York"));

        // Use the methods in NavigableSet interface
        System.out.println("lower(\"P\"): " + treeSet.lower("P"));
        System.out.println("higher(\"P\"): " + treeSet.higher("P"));
        System.out.println("floor(\"P\"): " + treeSet.floor("P"));
        System.out.println("ceiling(\"P\"): " + treeSet.ceiling("P"));
        System.out.println("pollFirst(): " + treeSet.pollFirst());
        System.out.println("pollLast(): " + treeSet.pollLast());
        System.out.println("New tree set: " + treeSet);

    }
}

 

Questions

  1. How do you create an instance of Set? How do you insert a new element in a set?

  1. How do you remove an element from a set? How do you find the size of a set?

  1. If two objects o1 and o2 are equal, what is o1.equals(o2) and o1.hashCode()== o2.hashCode()

  2. What are the differences between HashSet, LinkedHashSet, and TreeSet?

  3. How do you traverse the elements in a set?

  4. How do you sort the elements in a set using the compareTo method in the Comparable interface? How do you sort the elements in a set using the Comparator interface? What would happen if you added an element that could not be compared with the existing elements in a tree set?

  5. Suppose that set1 is a set that contains the strings red, yellow, and green and that set2 is another set that contains the strings red, yellow, and blue. Answer the

    following questions:

    • What are in set1 and set2 after executing set1.addAll(set2)?

    • What are in set1 and set2 after executing set1.add(set2)?

    • What are in set1 and set2 after executing set1.removeAll(set2)?

    • What are in set1 and set2 after executing set1.remove(set2)?

    • What are in set1 and set2 after executing set1.retainAll(set2)?

    • What is in set1 after executing set1.clear()?

Leave a Reply

Close Menu