How to use Set Collection in Java (HashSet, LinkedHashSet, TreeSet)


Use the following code for understanding how HashSet, TreeSet and LinkedHashSet are used in Java development environment.

package javacollectionsetexample;

import java.util.HashSet;
import java.util.Iterator;
import java.util.LinkedHashSet;
import java.util.TreeSet;

/**
 *
 * @author tunatore
 */
public class Main {
  /**
     * Collection is the super interface for the Set interface
     * Set is an interface
     * (public interface Set extends Collection)
     * SortedSet is a sub interface for the Set interface
     * (public interface SortedSet extends Set)
     * Implementing classes for the Set interface are:
     * AbstractSet, HashSet, LinkedHashSet, TreeSet
     * TreeSet is the only implementing class for the SortedSet interface
     */
     public static void main(String[] args) {

       Car car1 = new Car();
       Car car2 = new Car();
       Car car3 = new Car();
       Car car4 = new Car();
       Car car5 = new Car();

       car1.setName("SUBARU");
       car1.setModelYear(2000);
       car1.setMotorPower(3000);

       car2.setName("HONDA");
       car2.setModelYear(1999);
       car2.setMotorPower(2000);

       car3.setName("TOYOTA");
       car3.setModelYear(2004);
       car3.setMotorPower(1600);

       car4.setName("NISSAN");
       car4.setModelYear(2005);
       car4.setMotorPower(1200);

       car5.setName("HUNDAI");
       car5.setModelYear(2008);
       car5.setMotorPower(1400);

       System.out.println("\nTreeSet Example Starts\n");

       TreeSet<Car> carsTreeSet = new TreeSet<Car>();
       carsTreeSet.add(car1);
       carsTreeSet.add(car2);
       carsTreeSet.add(car3);
       carsTreeSet.add(car4);
       carsTreeSet.add(car5);

       //dublicate elements are not allowed in SETs
       //this statement will be ignored there will be only
       //one car5 element will be exist inside TreeSet
       carsTreeSet.add(car5);

        //Cars inside TreeSet will be sorted according to their motor power
        //Comparing objects will be done inside Car class by calling compareTo(Car carToCompare)
        //method internally from TreeSet collection class

       for (Iterator<Car> it = carsTreeSet.iterator(); it.hasNext();) {
       Car car = (Car) it.next();
       System.out.println("CAR name --> " + car.getName()
       + " Motor Power --> " + car.getMotorPower());
       }

       System.out.println("\nTreeSet DESCENDING order order\n");

      //if you need to get descending order use descending iterator

      for (Iterator<Car> it = carsTreeSet.descendingIterator(); it.hasNext();) {
      Car car = it.next();
      System.out.println("CAR name --> " + car.getName()
      + " Motor Power --> " + car.getMotorPower());
      }

       System.out.println("\nHashSet Example Starts\n");

       //HashSet Does not guarantee the order of its elements

       HashSet<Car> carHashSet = new HashSet<Car>();
       carHashSet.add(car1);
       carHashSet.add(car2);
       carHashSet.add(car3);
       carHashSet.add(car4);
       carHashSet.add(car5);
       //dublication of elements still not allowed
       carHashSet.add(car5);

      for (Iterator<Car> it = carHashSet.iterator(); it.hasNext();) {
      Car car = it.next();
      System.out.println("CAR name --> " + car.getName()
      + " Motor Power --> " + car.getMotorPower());
}

       System.out.println("\nLinkedHashSet Example Starts\n");

       //LinkedHashSet will maintain the order of Car elements
       //Car1 will be followed by car2,car3  ... car5
       //the ordering will be maintained according to the insertion order
       LinkedHashSet<Car> carLinkedHashSet = new LinkedHashSet<Car>();
       carLinkedHashSet.add(car1);
       carLinkedHashSet.add(car2);
       carLinkedHashSet.add(car3);
       carLinkedHashSet.add(car4);
       carLinkedHashSet.add(car5);

for (Iterator<Car> it = carLinkedHashSet.iterator(); it.hasNext();) {
Car car = it.next();
System.out.println("CAR name --> " + car.getName()
+ " Motor Power --> " + car.getMotorPower());
}
}
}

Car.java class



package javacollectionsetexample;

/**
*
* @author tunatore
*/

public class Car implements Comparable<Car>{

private String name;
private int motorPower;
private int modelYear;

public String getName() {
return name;
}

public void setName(String name) {
this.name = name;
}

public int getMotorPower() {
return motorPower;
}

public void setMotorPower(int motorPower) {
this.motorPower = motorPower;
}

public int getModelYear() {
return modelYear;
}

public void setModelYear(int modelYear) {
this.modelYear = modelYear;
}

    //this method will be used by TreeSet class
    //for sorting the car class elements according to Motor Power

public int compareTo(Car carToCompare) {

        //return zero if two objects are equal
        if (this.motorPower == carToCompare.getMotorPower() ) {
            return 0;
        } //return -1 if the current object is smaller than the object compared
        else if (this.motorPower < carToCompare.getMotorPower()) {
            return -1;
        } //return 1 if the current object is bigger than the object compared
        else {
            return 1;
        }

}

}

Sample Output of the program;

run:

TreeSet Example Starts

CAR name –> NISSAN Motor Power –> 1200
CAR name –> HUNDAI Motor Power –> 1400
CAR name –> TOYOTA Motor Power –> 1600
CAR name –> HONDA Motor Power –> 2000
CAR name –> SUBARU Motor Power –> 3000

TreeSet DESCENDING order

CAR name –> SUBARU Motor Power –> 3000
CAR name –> HONDA Motor Power –> 2000
CAR name –> TOYOTA Motor Power –> 1600
CAR name –> HUNDAI Motor Power –> 1400
CAR name –> NISSAN Motor Power –> 1200

HashSet Example Starts

CAR name –> NISSAN Motor Power –> 1200
CAR name –> TOYOTA Motor Power –> 1600
CAR name –> HONDA Motor Power –> 2000
CAR name –> HUNDAI Motor Power –> 1400
CAR name –> SUBARU Motor Power –> 3000

LinkedHashSet Example Starts

CAR name –> SUBARU Motor Power –> 3000
CAR name –> HONDA Motor Power –> 2000
CAR name –> TOYOTA Motor Power –> 1600
CAR name –> NISSAN Motor Power –> 1200
CAR name –> HUNDAI Motor Power –> 1400
BUILD SUCCESSFUL (total time: 1 second)

Exception may occurs like the following one if you do not  implement Comparable interface by Car class.

run:
Exception in thread “main” java.lang.ClassCastException: javacollectionsetexample.Car cannot be cast to java.lang.Comparable
        at java.util.TreeMap.put(TreeMap.java:542)
        at java.util.TreeSet.add(TreeSet.java:238)
        at javacollectionsetexample.Main.main(Main.java:55)
Java Result: 1


Download Source

Advertisements

2 thoughts on “How to use Set Collection in Java (HashSet, LinkedHashSet, TreeSet)

  1. If you are using comparable interface in Java and overriding compareTo method its worth noting that compareTo must be compatible with equals method in Java i.e. if two objects are equal via equals method compareTo method must return “0” for them, failing this may result in some subtle bug when you store those objects in collection class like TreeMap in Java

  2. Hello,I enjoy reading by way of your weblog, I wanted to leave a little comment to support you and wish you a fantastic continuation. Wishing you the best of luck for all your blogging efforts.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s