Sunday, July 28, 2013

How to Iterate Over a Map in Java

There are several ways of iterating over a Map in Java. Let see the common methods to iterate over Map.
Since all maps in Java implement Map interface, following techniques will work for any map implementation like HashMap, TreeMap, LinkedHashMap, Hashtable, etc.


1. This is the most common method and is preferable in most cases. Should be used if you need both map keys and values in the loop.


Map<Integer, Integer> map = new HashMap<Integer, Integer>();
for (Map.Entry<Integer, Integer> entry : map.entrySet()) {
    System.out.println("Key = " + entry.getKey() + ", Value = " + entry.getValue());
}

You will get NullPointerException if you try to iterate over a map that is null, so before iterating you should always check for null references.

2. Iterating over keys or values using For-Each loop.
If you need only keys or values from the map, you can iterate over keySet or values instead of entrySet.


//iterating over keys only
for (Integer key : map.keySet()) {
    System.out.println("Key = " + key);
}

//iterating over values only
for (Integer value : map.values()) {
    System.out.println("Value = " + value);
}


Performance advantage over entrySet iteration

3. Iterating using Iterator

Using Generics:

Map<Float, Float> map = new HashMap<Float, Float>();
Iterator<Map.Entry<Float, Float>> entries = map.entrySet().iterator();
while (entries.hasNext()) {
    Map.Entry<Float, Float> entry = entries.next();
    System.out.println("Key = " + entry.getKey() + ", Value = " + entry.getValue());
}


Without Generics:

Map map = new HashMap();
Iterator entries = map.entrySet().iterator();
while (entries.hasNext()) {
    Map.Entry entry = (Map.Entry) entries.next();
    Integer key = (Integer)entry.getKey();
    Integer value = (Integer)entry.getValue();
    System.out.println("Key = " + key + ", Value = " + value);
}

- You can use this techinque to iterate over keySet or values like discussed in case 2.
- It is the only way to iterate over a map in older versions of Java.

- It is the only method that allows you to remove entries from the map during iteration by calling iterator.remove().
- In terms of performance this techniques is equivalent to for-each iteration.


4. Iterating over keys and searching for values - inefficient


Map<Integer, Integer> map = new HashMap<Integer, Integer>();
for (Integer key : map.keySet()) {
    Integer value = map.get(key);
    System.out.println("Key = " + key + ", Value = " + value);
}

Alternative for method case 1- It is pretty slow and inefficient as getting values by a key might be time consuming


Other way :
for (Integer key : hm.keySet()) {
System.out.println("Key = " + key + " - " + map.get(key));
}


If you know anyone who has started learning Java, why not help them out! Just share this post with them. Thanks for studying today!...

Nested Interface in Java

As with classes, you can nest interfaces inside an outer class or another interface. The dynamics are similar to nested classes. However, keep in mind that the classes that ultimately implement these nested interfaces don't have the special access to the class members that a nested class does; instead,they behave just like normally declared classes.

An interface which is declared within another interface or class is known as nested interface.It is used to group related interfaces so that its easy to main. Nested interface must be referred by the outer interface or class, it can not be accessed directly.
Example :
Nested interface inside a class

class java {
    public interface latte {
        /* funtion name */
    }  
}


Nested interface inside a interface

interface java {
    public interface latte {
        /* funtion name */
    }   
}


Point to remember about nested interface.

  1. Nested interface must be public if is declared inside the interface
  2. It can have any access modifier if declared inside the class.
  3. a nested interface is automatically "static"
If a nested interface is declared like this

class java {
    public static interface latte {
        /* funtion name */
    }   
}


The static keyword in the this example is redundant and can be removed with no effect on semantics. Same like for "public" on interface methods and "public final" on interface fields - the modifiers are redundant.
An inner interface has to be static in order to be accessed. The interface isn't associated with instances of the class, but with the class itself, so it would be accessed with java.latte, like so:

public class Baz implements java.latte {
   ...

}


To better understand nested interface look at the Map.Entry static interface declared inside Map interface.
http://docs.oracle.com/javase/1.4.2/docs/api/java/util/Map.html
http://docs.oracle.com/javase/1.4.2/docs/api/java/util/Map.Entry.html


Example of Map.Entry interface


HashMap<String, String> map = new HashMap<String, String>();
for (Map.Entry<String, String> entry : map.entrySet())
{
    System.out.println(entry.getKey() + "/" + entry.getValue());

}


Entry is subinterface of Map ie accessed by Map.Entry


Nested Interfaces in Classes

The syntax for nested interfaces is the same as nested classes, but the results are quite different. Since you are defining only the interface and not the implementation, the user of the interface is free to implement the class any way he wants. A good example of a nested interface implementation is with a special collection


public class Inventory {
   public HashSet items;

   public Set getValues( ) {
      return Collections.unmodifiableSet(items);
   }

   public void addItem(final InventoryItem item) {
      items.add(item);
   }

   public Iterator iterator( ) {
      return items.iterator( );
   }

   public void removeElement(final InventoryItem item) {
      items.remove(item);
   }

   public static interface InventoryItem {
      public String getSKU( );
   }
}

In this example, the special collection named Inventory will contain only objects that implement the InventoryIteminterface (and therefore define the method getSKU( )). Furthermore, since you don't want to tie down the inventory items to a particular superclass, you make an interface for the inventory items, which allows the user to implement that interface as he sees fit.

There are only a few good reasons why you should use inner interfaces. One is to model a composition relationship without restricting the implementation of the composed object. In this case, you would need an inner interface to model the compositional relationship and to let the user of the interface decide on the implementation.

Nested interfaces are useful on rare occasions, but most of the time you can achieve the same results simply by declaring the interface in its own file.


Nested Interfaces in Interfaces

It is also possible to nest interfaces within other interfaces, although this is rarely done. The syntax is the same as with nested classes. Although using interfaces nested in other interfaces is less crazy than nesting classes within an interface, it is still pretty weird.

Essentially, when you nest an interface inside another interface, you are describing a compositional relationship among interfaces. Conceptually, it is a rather strange thing to do

Demo :

Map.java

public interface Map {
 interface Entry{
  void getKey();
  void getValue();
 }

}


JavaLatte.java

public class JavaLatte implements Map.Entry {
 @Override
 public void getKey() {
  System.out.println("This is key");
 }
 @Override
 public void getValue() {
  System.out.println("This is value");
 }

  public static void main(String myblog[]){
  Map.Entry entry=new JavaLatte(); //upcasting
  entry.getKey();
  entry.getValue();
 }

}


Can we create a class inside the interface?
Yes, OfCourse. If we define a class inside the interface, java compilter create a static nested class.
interface javalatte{
class TEST{}
}

Where we can use nested interface?
As you seen above, that with the help of nested interface you can get the key and value in a single loop.
According to me, there may a case where you need to get many values in a loop instead of getting one by one.

For instance, I need to get customer name, customer address and his bank balance in a loop. See the below example:

public class test1 {

 public static void main(String myblog[]){
  Map.Entry entry=new Bank(); //upcasting
  entry.getUserAddress();
  entry.getUserName();
  entry.getBalance();
 }

}

class Bank implements Map.Entry{

 public void getUserName() {
  System.out.println("This is pardeep");
 }

 public void getUserAddress() {
  System.out.println("India");
 }
 public void getBalance() {
  System.out.println("30m $");

 }
}

interface Map {
 interface Entry{
  void getUserAddress();
  void getUserName();
  void getBalance();
 }

}

Sample Output:
India
This is pardeep
30m $





Thanks for reading the post !
Please share or comment on this as this encourage me to write more :) 

Thursday, July 11, 2013

Visual Explanation of PL/SQL Joins

Tables may be joined in several ways. The most common technique is called an equijoin. A row is associated with one or more rows in another table based on the equality of column values or expressions. Tables may also be joined using a nonequijoin. In this case, a row is associated with one or more rows in another table if its column values fall into a range determined by inequality operators.















We'll take 2 tables, Table A and Table B


Table A Table B
ID Name ID Name
1 pardeep 1 oracle
2 kumar 2 pardeep
3 java 3 linkedin
4 latte 4 latte


INNER JOIN
The INNER JOIN keyword selects all rows from both tables as long as there is a match between the columns in both tables.
SQL INNER JOIN Syntax

SELECT column_name(s)
FROM table1
INNER JOIN table2
ON table1.column_name=table2.column_name;

or:

SELECT column_name(s)
FROM table1
JOIN table2
ON table1.column_name=table2.column_name;

Example:
SELECT * FROM TABLEA
INNER JOIN TABLEB 
ON TABLEA.NAME = TABLEB.NAME ;
ID Name ID Name
1 pardeep 2 pardeep
4 latte 4 latte

----------------------------------------------------------------------------------------------------------------



LEFT JOIN
The LEFT JOIN keyword returns all rows from the left table (table1), with the matching rows in the right table (table2). The result is NULL in the right side when there is no match.

SQL LEFT JOIN Syntax
Example 1

SELECT column_name(s)
FROM table1
LEFT JOIN table2
ON table1.column_name=table2.column_name;
or:

SELECT column_name(s)
FROM table1
LEFT OUTER JOIN table2
ON table1.column_name=table2.column_name;



Example 1
SELECT * FROM TABLEA
LEFT OUTER JOIN TABLEB
ON TABLEA.NAME = TABLEB.NAME;

ID Name ID Name
1 pardeep 2 pardeep
4 latte 4 latte
2 kumar
3 java

Special case Example 2 :


Example 2

SELECT * FROM TABLEA
LEFT OUTER JOIN TABLEB
ON TABLEA.NAME = TABLEB.NAME
WHERE TABLEB.ID IS NULL;





ID Name ID Name
2 kumar
3 java


--------------------------------------------------------------------------------



RIGHT JOIN The RIGHT JOIN keyword returns all rows from the right table (table2), with the matching rows in the left table (table1). The result is NULL in the left side when there is no match.

SQL RIGHT JOIN Syntax
Example 3

SELECT column_name(s)
FROM table1
RIGHT JOIN table2
ON table1.column_name=table2.column_name;
or:

SELECT column_name(s)
FROM table1
RIGHT OUTER JOIN table2
ON table1.column_name=table2.column_name;


Example 3
SELECT * FROM TABLEA
RIGHT OUTER JOIN TABLEBON TABLEA.NAME = TABLEB.NAME;


ID Name ID Name
1 pardeep 2 pardeep
4 latte 4 latte
1 oracle
3 linkedin

Special case Example 4
Example 4

SELECT * FROM TABLEA
RIGHT OUTER JOIN TABLEB
ON TABLEA.NAME = TABLEB.NAME
WHERE TABLEA.ID IS NULL;





ID Name ID Name
1 oracle
3 linkedin

--------------------------------------------------------------------------------


FULL OUTER JOIN
The FULL OUTER JOIN keyword returns all rows from the left table (table1) and from the right table (table2).

The FULL OUTER JOIN keyword combines the result of both LEFT and RIGHT joins.

SQL FULL OUTER JOIN Syntax
Example 5

SELECT column_name(s)
FROM table1
FULL OUTER JOIN table2
ON table1.column_name=table2.column_name;






Example 5SELECT * FROM TABLEA
FULL OUTER JOIN TABLEB
ON TABLEA.NAME = TABLEB.NAME;


Column1 Column2 ID Name
ID Name 1 oracle
2 pardeep
1 pardeep 3 linkedin
4 latte
4 latte
2 kumar
3 java

Special Case Example 6

Example 6
SELECT * FROM TABLEA
FULL OUTER JOIN TABLEB
ON TABLEA.NAME = TABLEB.NAME
WHERE TABLEA.ID IS NULL 
OR TABLEB.ID IS NULL;







ID Name ID Name
1 oracle
3 linkedin
2 kumar
3 java

Special Case
Let consider another table Table C




ID Name
1 pardeep
2 linkedin
3 java
4 blog





Query to extract that are common in all the tables

SELECT * FROM TABLEA INNER JOIN TABLEB
ON TABLEA.NAME=TABLEB.NAME
INNER JOIN TABLEC
ON TABLEC.NAME=TABLEB.NAME OR TABLEC.NAME=TABLEA.NAME;

NATURAL JOIN
The natural join is implemented using three possible join clauses that use the following keywords in different combinations: NATURAL JOIN, USING, and ON.

When the source and target tables share identically named columns, it is possible to perform a natural join between them without specifying a join column.The NATURAL JOIN keywords instruct Oracle to identify columns with identical names between the source and target tables. Thereafter, a join is implicitly performed between them

The general syntax for the NATURAL JOIN clause is as follows:

SELECT table1.column, table2.column
FROM table1
NATURAL JOIN table2;
The Natural JOIN USING Clause
The format of the syntax for the natural JOIN USING clause is as follows:

SELECT table1.column, table2.column
FROM table1JOIN table2 USING (join_column1, join_column2…);

While the pure natural join contains the NATURAL keyword in its syntax, theJOIN…USING syntax does not. An error is raised if the keywords NATURAL and USING occur in the same join clause. The JOIN…USING clause allows one or more equijoin columns to be explicitly specified in brackets after the USING keyword.

The Natural JOIN ON Clause
The format of the syntax for the natural JOIN ON clause is as follows:

SELECT table1.column, table2.column
FROM table1JOIN table2 ON (table1.column_name = table2.column_name);

Note:
The pure natural join and the JOIN…USING clauses depend on join columns with identical column names. The JOIN…ON clause allows the explicit specification of join columns, regardless of their column names





if you find this information useful, please comment.