Accessing a Collection in java
java programming and c, c++, Matlab, Python, HTML, CSS programming language, and new techniques news and any history.
java programming and c, c++, Matlab, Python, HTML, CSS programming language, and new techniques news and any history.
Accessing a Collection
To access, modify or remove any element from any collection we need to first find the element, for which we have to cycle through the elements of the collection. There are three possible ways to cycle through the elements of any collection.
- Using Iterator interface
- Using ListIterator interface
- Using for-each loop
Accessing elements using Iterator
Iterator Interface is used to traverse a list in forwarding direction, enabling you to remove or modify the elements of the collection. Each collection classes provide iterator() method to return an iterator.
import java.util.*;
class Test_Iterator
{
public static void main(String[] args)
{
ArrayList< String> ar = new ArrayList< String>();
ar.add("ab");
ar.add("bc");
ar.add("cd");
ar.add("de");
Iterator it = ar.iterator(); //Declaring Iterator
while(it.hasNext())
{
System.out.print(it.next()+" ");
}
}
}
Output :
ab bc cd de
Accessing element using ListIterator
ListIterator Interface is used to traverse a list in both forward and backward direction. It is available to only those collections that implement the List Interface.
import java.util.*; class Test_Iterator { public static void main(String[] args) { ArrayList< String> ar = new ArrayList< String>(); ar.add("ab"); ar.add("bc"); ar.add("cd"); ar.add("de"); ListIterator litr = ar.listIterator(); while(litr.hasNext()) //In forward direction { System.out.print(litr.next()+" "); } while(litr.hasPrevious()) //In backward direction { System.out.print(litr.next()+" "); } } }
Output :
ab bc cd de de cd bc ab
Using for-each loop
for-each
a version of for loop can also be used for traversing each element of a collection. But this can only be used if we don't want to modify the contents of a collection and we don't want any reverse access. for-each
the loop can cycle through any collection of the object that implements Iterable interface.import java.util.*; class ForEachDemo { public static void main(String[] args) { LinkedList< String> ls = new LinkedList< String>(); ls.add("a"); ls.add("b"); ls.add("c"); ls.add("d"); for(String str : ls) { System.out.print(str+" "); } } }
Output :
a b c d
Map Interface
Map stores data in key and value association. Both key and values are objects. The key must be unique but the values can be duplicate. Although Maps are a part of Collection Framework, they can not actually be called as collections because of some properties that they possess. However, we can obtain a collection-view of maps.
Interface | Description |
---|---|
Map | Maps unique key to value. |
Map. Entry | Describe an element in key and value pair in a map. Entry is a subinterface of Map. |
NavigableMap | Extends SortedMap to handle the retrieval of entries based on closest match searches |
SortedMap | Extends Map so that key are maintained in an ascending order. |
Commonly used Methods defined by Map
- boolean containsKey(Object k): returns true if the map contains k as key. Otherwise false.
- Object get(Object k): returns values associated with the key k.
- Object put(Object k, Object v) : stores an entry in map.
- Object putAll(Map m): put all entries from m in this map.
- Set keySet(): returns Set that contains the key in a map.
- Set entrySet() : returns Set that contains the entries in a map.
HashMap class
- HashMap class extends AbstractMap and implements Map interface.
- It uses a hash table to store the map. This allows the execution time of and
get()
put()
to remain same. - HashMap has four constructors.
HashMap() HashMap(Map< ? extends k, ? extends V> m) HashMap(int capacity) HashMap(int capacity, float fillratio)
- HashMap does not maintain the order of its element.
Example
import java.util.*;
class HashMapDemo
{
public static void main(String args[])
{
HashMap< String,Integer> hm = new HashMap< String,Integer>();
hm.put("a",new Integer(100));
hm.put("b",new Integer(200));
hm.put("c",new Integer(300));
hm.put("d",new Integer(400));
Set< Map.Entry< String,Integer> > st = hm.entrySet(); //returns Set view
for(Map.Entry< String,Integer> me:st)
{
System.out.print(me.getKey()+":");
System.out.println(me.getValue());
}
}
}
Output :
c 300 a 100 d 400 b 200
TreeMap class
- TreeMap class extends AbstractMap and implements NavigableMap interface.
- It creates Map, stored in a tree structure.
- A TreeMap provides an efficient means of storing key/value pair in an efficient order.
- It provides key/value pairs in sorted order and allows rapid retrieval.
Example
import java.util.*; class TreeMapDemo { public static void main(String args[]) { TreeMap< String,Integer> tm = new TreeMap< String,Integer>(); tm.put("a",new Integer(100)); tm.put("b",new Integer(200)); tm.put("c",new Integer(300)); tm.put("d",new Integer(400)); Set< Map.Entry< String,Integer> > st = tm.entrySet(); for(Map.Entryme:st) { System.out.print(me.getKey()+":"); System.out.println(me.getValue()); } } }
Output :
a 100 b 200 c 300 d 400
LinkedHashMap class
- LinkedHashMap extends HashMap class.
- It maintains a linked list of entries in a map in order in which they are inserted.
- LinkedHashMap defines the following constructor
LinkedHashMap() LinkedHashMap(Map< ? extends k, ? extends V> m) LinkedHashMap(int capacity) LinkedHashMap(int capacity, float fillratio) LinkedHashMap(int capacity, float fillratio, boolean order)
- It adds one new method.
removeEldestEntry()
This method is called by andput()
putAll()
By default this method does nothing. However, we can override this method to remove the oldest element in the map. Syntaxprotected boolean removeEldestEntry(Map.Entry
e)
EnumMap class
- EnumMap extends AbstractMap and implements Map interface.
- It is used for a key as enum
Comments
Post a Comment