java set collection code example

Example 1: set java

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 < 5; i++) {
            set.add(count[i]);
         }
         System.out.println(set);

         TreeSet sortedSet = new TreeSet<Integer>(set);
         System.out.println("The sorted list is:");
         System.out.println(sortedSet);

         System.out.println("The First element of the set is: "+ (Integer)sortedSet.first());
         System.out.println("The last element of the set is: "+ (Integer)sortedSet.last());
      }
      catch(Exception e) {}
   }
} 

OUTPUT:

              [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

Example 2: set java

A Set is a Collection that cannot contain duplicate elements.
  
The Set interface contains only methods inherited from Collection 
and adds the restriction that duplicate elements are prohibited.

Example 3: fusion vecteur ordonner java

public static int[] fusion2 ( int[] tab1, int[]tab2 ){
        int[] result= new int[tab1.length+tab2.length];
        int index1=0;
        int index2=0;
        int i=0;
        while (i<tab1.length+tab2.length && index1!=tab1.length && index2 != tab2.length){//on vérifie qu'on sort d'aucun des 3 tableaux sinon sa te fournit une erreur
            if (tab1[index1]<=tab2[index2]){ //si le tableau 1 est <= au tableau 2
                result[i]=tab1[index1];
                index1++;
            }
            else if(tab1[index1]>tab2[index2]){ //si le tableau 1 est > au tableau 2
                result[i]=tab2[index2];
                index2++;
            }
            i++;
        }
        //dans le cas ou les deux tableaux ne font pas la même taille
        while (index1 < tab1.length){ //le premier tableau est plus grand que le second
            result[i]=tab1[index1];
            i++;
            index1++;
        }
        while (index2 < tab2.length){ //la c'est le second 
            result[i]=tab2[index2];
            i++;
            index2++;
        }
        return result;
    }

Tags:

Java Example