How to use a Map in Java (HashMap,LinkedHashMap)


Use the following source code;

Product.java
package javamapexample;

/**
 *
 * @author tunatore
 */
public class Product {

private int id;
private String name;
private int price;

public Product(int id,String name,int price) {
this.id = id;
this.name = name;
this.price = price;
}
/**
* @return the id
*/
public int getId() {
return id;
}

/**
* @param id the id to set
*/
public void setId(int id) {
this.id = id;
}

/**
* @return the name
*/
public String getName() {
return name;
}

/**
* @param name the name to set
*/
public void setName(String name) {
this.name = name;
}

/**
* @return the price
*/
public int getPrice() {
return price;
}

/**
* @param price the price to set
*/
public void setPrice(int price) {
this.price = price;
}

}

Main.java

package javamapexample;

import java.util.HashMap;
import java.util.Iterator;
import java.util.LinkedHashMap;
import java.util.Map;

/**
 *
 * @author tunatore
 */
public class Main {

/**
* @param args the command line arguments
*/
public static void main(String[] args) {

     //Lets create first products by using Product class

        Product p1 = new Product(1,”car”,10000);
        Product p2 = new Product(2,”computer”,1000);
        Product p3 = new Product(3,”phone”,400);
        Product p4 = new Product(4,”speakers”,100);
        Product p5 = new Product(5,”speakers2″,125);

        Map<String,Product> productMap = new HashMap<String, Product>();
        productMap.put(“car”, p1);
        productMap.put(“computer”, p2);
        productMap.put(“phone”, p3);
        productMap.put(“speakers”, p4);

        //what will be happened if a same key is inserted again
        //this will replace the old product with a new one
productMap.put(“speakers”, p4);

       //HashMap allows programmers to have only one Null key and many null values

      productMap.put(null, p5);

     //productMap.put(null, null); VALID
    //productMap.put(“phone”, null); VALID

System.out.println(“getting the phone element (id for the phone) with key phone –> ” + productMap.get(“phone”).getId() );

        // Iteration starts
        //ordering of the elements in a HashMap is not sorted
        //so that ordering will be unpredictable
        //use TreeMap if you want ordering
Iterator it = productMap.keySet().iterator();
while (it.hasNext()) {
Object key = it.next();
System.out.println(“key –> ” + key + ” value –> ” + ” id -> ” + productMap.get(key).getId()  + ” name -> ” + productMap.get(key).getName());
}

System.out.println(“\nLinkedHashMap starts\n”);

        Map<String,Product> productMapLinked = new LinkedHashMap<String, Product>();
        productMapLinked.put(“1”, p2);
        productMapLinked.put(“2”, p3);
        productMapLinked.put(“3”, p1);

Iterator it2 = productMapLinked.keySet().iterator();
while (it2.hasNext()) {
Object key = it2.next();
System.out.println(“key –> ” + key + ” value –> ” + productMapLinked.get(key).getName());
}

     //If you use TreeMap in your application
        //You  will need to override equals() and hashCode()

}

}

Sample output;

run:
getting the phone element (id for the phone) with key phone –> 3

HashMap starts

key –> null value –>  id -> 5 name -> speakers2
key –> computer value –>  id -> 2 name -> computer
key –> car value –>  id -> 1 name -> car
key –> phone value –>  id -> 3 name -> phone
key –> speakers value –>  id -> 4 name -> speakers

LinkedHashMap starts

key –> 1 value –> computer
key –> 2 value –> phone
key –> 3 value –> car
BUILD SUCCESSFUL (total time: 1 seconds)
Download Source

Advertisements

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

How to read properties file using JAVA


First create a properties file like below; And put it the package folder where you can read and access this file

config.properties

# config.properties
# author: tuna tore
!this is a comment
#this is a comment too
! \ means a multiline is exist

keyForProperty1=Hello
keyForProperty2=Hello World!!!
123=an integer property is OK!

keyForProperty3= the value of the property3 \
                 new line \
                 new line2

And code a Main.java file like below;

package readingpropertiesfileexample;
import java.io.InputStream;
import java.util.Iterator;
import java.util.Properties;

/**
 *
 * @author tunatore
 */
public class Main {

    public static void main(String[] args) {

     try {          
 
            InputStream inputStream = Main.class.getResource(“config.properties“).openStream();
            Properties properties = new Properties();
            properties.load(inputStream);
               
            String property1 = properties.getProperty(“keyForProperty1“);
            String property2 = properties.getProperty(“keyForProperty2“);           
            String property3 = properties.getProperty(“keyForProperty3“);
            String property4 = properties.getProperty(“123“);

            System.out.println(“property1: ” + property1);
            System.out.println(“property2: ” + property2);
            System.out.println(“multiline property3: ” + property3);
            System.out.println(“integer property4: ” + property4);

            System.out.println(“#######Iteration over keyset#######STARTS…..”);

            for (Iterator it = properties.keySet().iterator(); it.hasNext();) {
                    String propertyKey = (String) it.next();
                    System.out.println(“Iteration key: ” + propertyKey + ” key value: ”
                            + properties.getProperty(propertyKey));
            }
            System.out.println(“#######Iteration over keyset#######ENDS…….”);

            inputStream.close();

        } catch (Exception ex) {
            System.out.println(ex.getMessage());

        }
    }
}

After running the output is;

run:
property1: Hello
property2: Hello World!!!
multiline property3: the value of the property3 new line new line2
integer property4: an integer property is OK!
#######Iteration over keyset#######STARTS…..
Iteration key: 123 key value: an integer property is OK!
Iteration key: keyForProperty3 key value: the value of the property3 new line new line2
Iteration key: keyForProperty2 key value: Hello World!!!
Iteration key: keyForProperty1 key value: Hello
#######Iteration over keyset#######ENDS…….
BUILD SUCCESSFUL (total time: 0 seconds)

Download Source

Java Comparable Interface example


Comparable interface is  implemented by a Java class for comparing the equality or difference with other instances of this comparable class.
The comparavble class will handle comparing operation by itself.

Comparable interface structure

public interface Comparable {
public int compareTo(T o);
}

An object must implement compareTo method of Comparable interfaces like the code below;

package comparableandcomparatorexample;

/**
 *
 * @author tunatore
 */
public class Box implements Comparable<Box> {

    private long height;
    private long width;
    private long length;
    private String boxName;

    public Box(long height, long width, long length,String name) {
        this.height = height;
        this.width = width;
        this.length = length;
        this.boxName = name;

    }

    /**
     * @return the height
     */
    public long getHeight() {
        return height;
    }

    /**
     * @param height the height to set
     */
    public void setHeight(long height) {
        this.height = height;
    }

    /**
     * @return the width
     */
    public long getWidth() {
        return width;
    }

    /**
     * @param width the width to set
     */
    public void setWidth(long width) {
        this.width = width;
    }

    /**
     * @return the length
     */
    public long getLength() {
        return length;
    }

    /**
     * @param length the length to set
     */
    public void setLength(long length) {
        this.length = length;
    }

    /**
     * @return the boxName
     */
    public String getBoxName() {
        return boxName;
    }

    /**
     * @param boxName the boxName to set
     */
    public void setBoxName(String boxName) {
        this.boxName = boxName;
    }

    public int compareTo(Box boxToCompare) {
        //return zero if two objects are equal
        if (this.calculateVolume() == boxToCompare.calculateVolume()) {
            return 0;
        } //return -1 if the current object is smaller than the object compared
        else if (this.calculateVolume() < boxToCompare.calculateVolume()) {
            return -1;
        } //return 1 if the current object is bigger than the object compared
        else {
            return 1; //if (this.calculateVolume() > boxToCompare.calculateVolume())
        }
    }

    public long calculateVolume() {
        //Volume = (height.(width).(length)
        return this.height * this.width * this.length;
    }

    public String printVolume() {

        return this.boxName + “‘s volume: ” + String.valueOf(calculateVolume());
    }
}

Create a Main class for testing sorting

package comparableandcomparatorexample;

import java.util.ArrayList;
import java.util.Collections;
import java.util.Iterator;
import java.util.List;

/**
 *
 * @author tunatore
 */
public class Main {

    /**
     * @param args the command line arguments
     */
    public static void main(String[] args) {

       ListboxList = new ArrayList();

       Box box1 = new Box(5,5,5,”box1″);
       Box box2 = new Box(10,10,10,”box2″);
       Box box3 = new Box(100,100,100,”box3″);
       Box box4 = new Box(2,2,2,”box4″);
       Box box5 = new Box(1,1,1,”box5″);

       boxList.add(box1);
       boxList.add(box2);
       boxList.add(box3);
       boxList.add(box4);
       boxList.add(box5);

       Collections.sort(boxList); //compareTo methods of the Box objects will be called
       //and the sorting will be done according to the return values

       for (Iterator<Box> it = boxList.iterator(); it.hasNext();) {
            Box boxCurrent = it.next();
            //sorted boxes will be printed
            System.out.println(“natural sorting:” + boxCurrent.printVolume());

        }

       Collections.sort(boxList,Collections.reverseOrder()); //compareTo methods of the Box objects will be called
       //and the reverse sorting will be done according to the return values
       System.out.print(“\n”); //new line

       for (Iterator<Box> it = boxList.iterator(); it.hasNext();) {
            Box boxCurrent = it.next();
            //sorted boxes will be printed
            System.out.println(“reverse sorting:” + boxCurrent.printVolume());

        }

    }

}

the output is;

run:
natural sorting:box5’s volume: 1
natural sorting:box4’s volume: 8
natural sorting:box1’s volume: 125
natural sorting:box2’s volume: 1000
natural sorting:box3’s volume: 1000000

reverse sorting:box3’s volume: 1000000
reverse sorting:box2’s volume: 1000
reverse sorting:box1’s volume: 125
reverse sorting:box4’s volume: 8
reverse sorting:box5’s volume: 1
BUILD SUCCESSFUL (total time: 0 seconds)

Download Source Code

java.util.zip Zip a file example


package test;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.zip.ZipEntry;
import java.util.zip.ZipOutputStream;

/**
 *
 * @author tunatore
 */
public class CreatingZIPfile {

    public void createZipFile() {

        try {

            File inputFile = new File(“C:\\test.txt”);
            File zipFile = new File(“C:\\compressed.zip”);

            //Create input and output streams
            FileInputStream inStream = new FileInputStream(inputFile);
            ZipOutputStream outStream = new ZipOutputStream(new FileOutputStream(zipFile));

            // Add a zip entry to the output stream
            outStream.putNextEntry(new ZipEntry(inputFile.getName()));

            byte[] buffer = new byte[Byte.MAX_VALUE];
            int bytesRead;

            //read from the input stream
            //write to the output stream
            while ((bytesRead = inStream.read(buffer)) > 0)
            {
                outStream.write(buffer, 0, bytesRead);
            }

            //Close zip entry and file streams
            outStream.closeEntry();

            outStream.close();
            inStream.close();

        } catch (IOException ex) {
            ex.printStackTrace();
        }
    }

    public static void main(String[] args)
    {
        new CreatingZIPfile().createZipFile();
    }
}