Thursday, November 7, 2013

What is the difference between an Ordered and Sorted Collection?



Ordered:
- An ordered collection means that the elements of the collection have a specific order. The order is independent of the value. A List is an example.

Sorted:
- A sorted collection means that not only does the collection have order, but the order depends on the value of the element. A SortedSet is an example.

-- In contrast, a collection without any order can maintain the elements in any order. A Set is an example.



Wednesday, November 6, 2013

Usage of foreach loop inside foreach loop, and also an example of iterating a List of Map objects ....9/10

Hi,

This page explain how to iterate a List object of Map objects using foreach loops.

Take a class Test.java

source :
package com.nagarjuna.core.collections:
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class Test {

public static void main(String[] args) {

List> lMap = new ArrayList>();

Map m = new HashMap();
m.put("1", "one");
m.put("3", "three");
m.put("2", "two");
m.put("0", "zero");

Map m1 = new HashMap();
m1.put("1", "one");
m1.put("0", "zero");
m1.put("2", "two");
m1.put("3", "three");

Map m2 = new HashMap();
m2.put("3", "three");
m2.put("1", "one");
m2.put("2", "two");
m2.put("0", "zero");

Map m3 = new HashMap();
m3.put("1", "one");
m3.put("2", "two");
m3.put("3", "three");
m3.put("0", "zero");

// now trying to put these map objects into a lis object


lMap.add(m1);
lMap.add(m2);
lMap.add(m3);
lMap.add(m2);
lMap.add(m);


// trying to print the key value pairs of each map from the list above

for (Map map : lMap) { //for each map obeject in list object
      System.out.println(lMap.indexOf(map)); //will print the index number of current map object in list
for (String key : map.keySet()) { // for each map's keyset object..iterating this keyset

System.out.println(key + ":" + map.get(key));
}//end inner loop

System.out.println("----------------------------------"); // end of first index of list object
}//end outer loop

}

}//end class


Just observe the above foreach loop code to understand how to use when we have to iterate a collection of collection of like this.



Tuesday, November 5, 2013

Usage of for loop styles in Collections..9/10

Example 1:

for (int i=0, n=list.size(); i < n; i++)
         list.get(i);
 
runs faster than this loop:
     for (Iterator i=list.iterator(); i.hasNext(); )
         i.next();

source: http://docs.oracle.com/javase/6/docs/api/java/util/RandomAccess.html