Various ways to iterate over commonly used collections viz ArrayList,HashMap,HashSet

Hello Friends,

In this tutorial ,we will see how to iterate over very commonly used collections viz. ArrayList, HashMap and HashSet.





1. How to iterate over an ArrayList

a)  Normal for loop

List list = new ArrayList();
list.add("a");
list.add("b");
for (int i = 0; i < list.size(); i++) {
       System.out.println(list.get(i));
}

b) Using Iterator - before Java 5

List list = new ArrayList();
list.add("a");
list.add("b");
for (Iterator itrList= list.iterator(); itrList.hasNext();) {
 System.out.println(itrList.next());
}

c) Using Iterator with For loop -After Java 5

List<String> list = new ArrayList<String>();
list.add("a");
list.add("b");
for (Iterator<String> itrList= list.iterator(); itrList.hasNext();) {
 System.out.println(itrList.next());
}

d) Using Iterator with while loop -After Java 5

List<String> list = new ArrayList<String>();
list.add("a");
list.add("b");
Iterator<String> itrList = list.iterator();
while(itrList.hasNext()){
   System.out.println(itrList.next());
}

e) Using ListIterator  

To traverse in forward direction

List<String> list = new ArrayList<String>();
list.add("a");
list.add("b");
ListIterator< String> lstItr = list.listIterator();
while(lstItr.hasNext()){
 String str = (String)lstItr.next();
 System.out.println(str);
}

To traverse in backward direction 

List<String> list = new ArrayList<String>();
list.add("a");
list.add("b"); 
ListIterator< String> lstItr = list.listIterator();
while(lstItr.hasPrevious()){
 String str = (String)lstItr.previous();
 System.out.println(str);

}

f) Using enhanced For Loop : Java 5 onwards

List<String> list = new ArrayList<String>();
list.add("a");
list.add("b");
for(String str : list){
 System.out.println(str);
}

g) using Lamda expression : Java 8 onwards

List<String> list = new ArrayList<String>();
list.add("a");
list.add("b");
list.forEach(listVal-> System.out.println(listVal));

2.How to iterate over HashMap


a) Using iterator  -Before Java 5

Map map = new HashMap();
map.put("a","a1");
map.put("b","b1");
Iterator itrMap = map.entrySet().iterator();
while (itrMap .hasNext()) {
    Map.Entry entry = (Map.Entry) itrMap.next();
    String key = (String)entry.getKey();
    String value = (String)entry.getValue();
    System.out.println("Key = " + key + ", Value = " + value);
}


b) Using iterator - After Java 5 

Map<String, String> map = new HashMap<String, String>();
map.put("a","a1");
map.put("b","b1");

Set<Entry<String,String>> entrySet = map.entrySet();
Iterator<Entry<String,String>> itrEntrySet  =entrySet .iterator();
     while (itrEntrySet.hasNext()) {
     Entry<String, String> entry = (Entry<String,String>)itrEntrySet.next();
     System.out.println("Key = " + entry.getKey() + ", Value = " + entry.getValue());
}

c) Using enhanced for loop - After Java 5 :Iterating over keys as well as values

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

d) Using enhanced for loop - After Java 5 :Iterating only over keys or values 

Map<String, String> map = new HashMap<String, String>();
map.put("a","a1");
map.put("b","b1");
for (String key : map.keySet()) {
    System.out.println("Key = " + key);
}
//iterating over values only
for (String value : map.values()) {
    System.out.println("Value = " + value);
}

e) Iterating over keys and searching for values 


Map<String, String> map = new HashMap<String, String>();
map.put("a","a1");
map.put("b","b1");
Map<String, String> map = new HashMap<String, String>();
for (String key : map.keySet()) {
    String value = map.get(key);
    System.out.println("Key = " + key + ", Value = " + value);
}

f) Using Lamda expression - Java 8 onwards

Map<String, String> map = new HashMap<String, String>();
map.put("a","a1");
map.put("b","b1");
map.forEach( (k,v) -> System.out.println("Key: " + k + ": Value: " + v));

3.How to iterate over HashSet

a) Using  Iterator  - Before Java 4

Set set = new HashSet();
set.add("x");
set.add("y");
Iterator itrSet = set.iterator();
while (itrSet .hasNext()) {
    System.out.println(itrSet.next());
}  

b) Using Iterator - After Java 5

Set<String> set = new HashSet<String>();
set.add("x"); 
set.add("y");
Iterator<String> itrSet = set.iterator();
while (itrSet .hasNext()) {
      System.out.println(itrSet .next());

c)Using Enhanced For loop - After Java 5

Set<String> set = new HashSet<String>();
set.add("x"); 
set.add("y");
for (String s : set) {
 System.out.println(s);
}

d) Using Lamda expression - After Java 8

Set<String> set = new HashSet<String>();
set.add("x"); 
set.add("y");
set.forEach(val ->System.out.println(val));

Hope this was helpful.Any feedback ,suggestion,questions on the post are most welcome.


How to make object eligible for garbage collection

Dear Friends,

In this tutorial I would try to explain what is garbage collection in Java and How to make objects eligible for Garbage collection.

In the language like C,a programmer need to manually do the memory management himself/herslef by allocating memory programmatically and then de-allocating memory programmatically,but Java provides automatic memory management facility,wherein a programmer need not take care of allocating/de-allocating memory,but there is utility which is part of JVM which do it for programmer automatically and we call is as Mr. Garbage Collector.Don't go on its name,it's a big guy actually,which does pretty decent job for programmer :)


What are Exceptions and types of Exceptions in Java

Hi Friends,

In this tutorial I would try to explain what are exceptions and types of exceptions in Java.

What are Exceptions?

Exception as its name suggest is the exceptional flow in your program rising due to the unexpected run time condition.For Example : FileNotFoundException.You may have written a code which would be reading a file placed at file system and source of that file is some other system.While writing code you are expecting that file at that particular location will always be there,but it is possible due to some issue in another system,that system or application would not have placed file at that location,which will result in FileNotFoundException in your program.Now this is a exceptional flow,as in normal or happy scenario, file would have been there and your program would have read the file and would have exit gracefully.Now you would like your program to complete gracefully if such kind of exceptional scenario arises.for that you can surround your code which is prone to exception by try block and can handle exceptional scenario in Catch block.