Loading Posts...

Java Set Example | Set Example In Java Tutorial

Java Set Example | Set Example In Java Tutorial

Java Set Example | Set Example In Java Tutorial is today’s topic. In Java, Set is a collection of objects that contains no duplicate values. The following are the key features of a set. Set is the interface which extends Collection. It is the unordered collection of objects in which duplicate values cannot be stored. Set is implemented by the HashSet, LinkedHashSet or TreeSet (sorted representation). 

Java Set Example

Set has various methods to add, remove clear, size, etc. to enhance the usage of an interface. Set also adds the stronger contract on a behavior of the equals and hashCode operations, allowing the Set instances to be compared meaningfully even if their implementation types differ.

Features of Set in Java

A Set is an interface which extends the Collection interface. An Interface is the collection of abstract methods. A class in java implements the interface to inherit and define these abstract methods of the interface.)

The Set contains all unique values. I.e., The duplicate values cannot be stored in the Set. If you try to add any value into the set that is already present in it, it will simply skip adding those values again and will retain only one unique element as its every element. 

The Set interface is implemented by the following classes: HashSet, TreeSet, etc. 

What this means is that the HashSet class, the TreeSet class (and all the other capable classes) implement the interface Set and inherit its abstract members and now they can define these members in their body. Through this, these classes can implement the set properties and the collection properties. 

When the HashSet Class implements the Set, then we get our values in an unordered manner because the HashSet stores the values in the hashtable and while displaying the value, it shows the values according to the locations (nearest) in which they are stored.

See the code example.

import java.sql.SQLOutput;
import java.util.HashSet;
import java.util.Set;

public class Set_Demo1 {
    public static void main(String[] args) {
        Set fruits = new HashSet();

        fruits.add("Apple");
        fruits.add("Banana");
        fruits.add("Orange");
        fruits.add("Grapes");
        fruits.add("Kiwi");

        System.out.println(fruits);

    }
}

See the output.

Features of Set

 

 

Here, you can see that the fruits displayed on the output are neither in the order in which they were entered nor they are in ascending or descending order (according to lexical order).

Is the TreeSet is implementing the Set, then you get the output in ascending order because, in the Background of the TreeSet class, it follows such algorithm which sorts the values in ascending order while storing them? See the following code.

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

public class Set_Demo2 {
    public static void main(String[] args) {
        Set fruits = new TreeSet();

        fruits.add("Apple");
        fruits.add("Banana");
        fruits.add("Orange");
        fruits.add("Grapes");
        fruits.add("Kiwi");

        System.out.println(fruits);

    }
}

See the output.

 

Features of Set

Here, you can see that the fruits displayed in the output are in ascending order according to their first letters.

A set follows all the properties of collections, but it also has some surplus features which makes it unique. The following are the key features which make a set different from other Collections.

  1. No duplicate elements.
  2. The mathematical sets can be well implemented using The Java Set. Operations like Set Union, Set6 Intersection and Set Difference can easily be performed using readymade methods, i.e. addAll() , retainAll() and removeAll(). 

The other properties of a set remain the same as all the rest of the Collections such as the Lists.

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

public class SetDemo {
    public static void main(String[] args) {

        Set setA = new TreeSet();
        Set setB = new TreeSet();

        for (int i = 0; i < 20; i += 2)
            setA.add(i); // Numbers divisible by 2

        for (int i = 0; i < 20; i += 3)
            setB.add(i); // Numbers divisible by 3

        // Union of setA and setB
        Set A_union_B = new TreeSet<>(setA);
        A_union_B.addAll(setB);
        System.out.println("Numbers Divisible by either 2 or 3 or both are: " + A_union_B);

        // Intersection of setA and setB
        Set A_intersects_B = new TreeSet<>(setA);
        A_intersects_B.retainAll(setB);
        System.out.println("Numbers Divisible by both 2 and 3 are: " + A_intersects_B);

        // Difference of setA and setB
        Set A_minus_B = new TreeSet<>(setA);
        A_minus_B.removeAll(setB);
        System.out.println("Numbers Divisible by 2 but not 3 are: " + A_minus_B);

        Set B_minus_A = new TreeSet<>(setB);
        B_minus_A.removeAll(setA);
        System.out.println("Numbers Divisible by 3 but not 2 are: " + B_minus_A);
    }
}

See the output.

 

Set Example In Java Tutorial

Java Set Methods

Sr.No. Method & Description
1 add( )

It adds an object to the collection.

2 clear( )

It removes all objects from the collection.

3 contains( )

It returns true if a specified object is an element within the collection.

4 isEmpty( )

It returns true if the collection has no elements.

5 iterator( )

It returns the Iterator object for a collection, which may be used to retrieve the object.

6 remove( )

It removes the specified object from a collection.

7 size( )

It returns a number of elements in the collection.

Finally, the Java Set Example | Set Example In Java Tutorial is over.

Recommended Posts

Thread Pools In Java Example

Java List Interface Example

Java Merge Sort Program

Insertion Sort In Java Example

For-each Loop In Java Example

The post Java Set Example | Set Example In Java Tutorial appeared first on AppDividend.

Get Free Email Updates!

Signup now and receive an email once I publish new content.

I agree to have my personal information transfered to MailChimp ( more information )

I will never give away, trade or sell your email address. You can unsubscribe at any time.

user

The author didnt add any Information to his profile yet

Loading Posts...