What is a set in Java?

Java 8Object Oriented ProgrammingProgramming

A Set is a Collection that cannot contain duplicate elements. It models the mathematical set abstraction.

The Set interface contains only methods inherited from Collection and adds the restriction that duplicate elements are prohibited.

Set also adds a stronger contract on the behavior of the equals and hashCode operations, allowing Set instances to be compared meaningfully even if their implementation types differ.


import java.util.*;
public class SetDemo {
   public static void main(String args[]) {

      int count[] = {34, 22,10,60,30,22};
      Set<Integer> set = new HashSet<Integer>();
      try {
         for(int i = 0; i < 6; i++) {
         TreeSet sortedSet = new TreeSet<Integer>(set);
         System.out.println("The sorted list is:");
         System.out.println("The First element is: "+ (Integer)sortedSet.first());
         System.out.println("The last element is: "+ (Integer)sortedSet.last());
      catch(Exception e) {}


[34, 22, 10, 60, 30]
The sorted list is:
[10, 22, 30, 34, 60]
The First element of the set is: 10
The last element of the set is: 60
Updated on 30-Jul-2019 22:30:21