Sets in Java

Introduction

Sets in Java closely relate to the mathematical definition of sets. Sets are unordered collections of objects. Like mathematical sets, Java also does not allow duplicate elements in a set. However, a null element can be added to a set. The Set interface is part of the java.util package and extends the Collection interface. The interface has several methods to manipulate elements in a set like search for elements, update the set, and perform operations like concatenation, difference, and intersection.

Declaration Syntax: public interface Set extends Collection

Creating a Simple Set – Example

import java.util.*;
public class SetDemo
{
public static void main (String args [])
{
Set <String> set = new HashSet <String> ();

set.add(“Hello”);
set.add(“World”);
set.add(“Sample”);
set.add(“Program”);

System.out.println(set);
}
}

 

OUTPUT

[Hello, World, Sample, Program]

Set Objects

Set <Obj> set = new HashSet <Obj> ();

Here Obj determines the type of object you want the set to store.

Simple Set Operations

  • Intersection: Intersection returns the common elements between two or more sets.
  • Union: Union returns the concatenation of two sets excluding all duplicate elements.
  • Difference: Difference returns the elements that are present in the current set but not in the set being compared to.

Example

In this example, we will demonstrate the three basic operations as described above: Intersection, Union, and Difference.

import java.util.*;
public class SetExample
{
public static void main(String args[])
{
Set<Integer> a = new HashSet<Integer>();
a.addAll(Arrays.asList(new Integer[] {1, 3, 2, 4, 8, 9, 0}));
Set<Integer> b = new HashSet<Integer>();
b.addAll(Arrays.asList(new Integer[] {1, 3, 7, 5, 4, 0, 7, 5}));

Set<Integer> union = new HashSet<Integer>(a);
union.addAll(b);
System.out.print("Union of the two Set");
System.out.println(union);

Set<Integer> intersection = new HashSet<Integer>(a);
intersection.retainAll(b);
System.out.print("Intersection of the two Set");
System.out.println(intersection);

Set<Integer> difference = new HashSet<Integer>(a);
difference.removeAll(b);
System.out.print("Difference of the two Set");
System.out.println(difference);
}
}

OUTPUT

Union of the two sets [0, 1, 2, 3, 4, 5, 7, 8, 9] Intersection of the two Set [0, 1, 3, 4] Difference of the two sets [2, 8, 9]

Leave a comment

This site uses Akismet to reduce spam. Learn how your comment data is processed.