HashMap implements Map

HashMap implements Map:-
 
The HashMap class is roughly equivalent to Hashtable, except that it is unsynchronized and permits nulls.
The two most important HashMap's methods are:
- get( Object key ) - returns the value associated with specified key in this hash map, or null if there is no value for this key
- put(K key, V value) - associates the specified value with the specified key in this map
There are some other useful HashMap's methods:
- containsKey(Object key) - (boolean) returns true if this map contains a value for the specified key
- values() - returns a collection of the values contained in this map
- keySet() - returns a set view of the keys contained in this map
- remove(Object key) - removes the mapping for key from this map if present
- isEmpty() - (boolean) returns true if this map contains no key-value mappings
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import java.util.Set;

public class HashMapExample {

    public static void main(String[] args) {

        HashMap<Object,String> hm=new HashMap<Object,String>();

        // adding or set elements in HashMap by put method key and value pair
        hm.put(new Integer(2), "Two");
        hm.put(new Integer(1), "One");
        hm.put(new Integer(3), "Three");
        hm.put(new Integer(4), "Four");

        // Get hashmap in Set interface to get key and value
        Set s=hm.entrySet();

        // Move next key and value of HashMap by iterator
        Iterator it=s.iterator();

        while(it.hasNext())
        {
            // key=value separator this by Map.Entry to get key and value
            Map.Entry m =(Map.Entry)it.next();

            // getKey is used to get key of HashMap
            int key=(Integer)m.getKey();

            // getValue is used to get value of key in HashMap
            String value=(String)m.getValue();

            System.out.println("Key :"+key);
            System.out.println("value :"+value);
        }
    }
}
Output
Key :1
value :One
Key :2
value :Two
Key :3
value :Three
Key :4
value :Four

PriorityQueue implements Queue

PriorityQueue implements Queue:- In a priority queue, items are ordered by key value, so that the item with the lowest key (or in some implementations the highest key) is always at the front. Items are inserted in the proper position to maintain the order.

import java.util.PriorityQueue;

public class PriorityQueueExample {
    public static void main(String[] args) {
        PriorityQueue<string> priorityQueue = new PriorityQueue<string>();
        priorityQueue.add("test1");
        priorityQueue.add("test2");
        priorityQueue.add("test3");
        priorityQueue.add("test4");
        priorityQueue.add("test5");
        System.out.println(priorityQueue);
    }
}

output:
[test1, test2, test3, test4, test5]

LinkedList implements List

LinkedList implements List, Queue:- Linked Lists are a very common way of storing arrays of data. The major benefit of linked lists is that you do not specify a fixed size for your list. The more elements you add to the chain, the bigger the chain gets. .When accessed via the Queue interface, LinkedList behaves as a FIFO queue.

Linked list implementation of the List interface. Implements all optional list operations, and permits all elements (including null). In addition to implementing the List interface, the LinkedList class provides uniformly named methods to get, remove and insert an element at the beginning and end of the list. These operations allow linked lists to be used as a stack, queue, or double-ended queue (deque).
Note that this implementation is not synchronized.

import java.util.*;
class LinkedListDemo {
public static void main(String args[]) {
// create a linked list
LinkedList ll = new LinkedList();
// add elements to the linked list
ll.add("F");
ll.add("B");
ll.add("D");
ll.add("E");
ll.add("C");
ll.addLast("Z");
ll.addFirst("A");
ll.add(1, "A2");
System.out.println("Original contents of ll: " + ll);
// remove elements from the linked list
ll.remove("F");
ll.remove(2);
System.out.println("Contents of ll after deletion: "
+ ll);
// remove first and last elements
ll.removeFirst();
ll.removeLast();
System.out.println("ll after deleting first and last: "
+ ll);
// get and set a value
Object val = ll.get(2);
ll.set(2, (String) val + " Changed");
System.out.println("ll after change: " + ll);
}
}
The output from this program is shown here:
Original contents of ll: [A, A2, F, B, D, E, C, Z]
Contents of ll after deletion: [A, A2, D, E, C, Z]
ll after deleting first and last: [A2, D, E, C]
ll after change: [A2, D, E Changed, C]

Vector implements List

Vector implements List, RandomAccess:- This class is roughly equivalent to ArrayList except it is Synchronized.

Syntax of some important method of Vector class. Given below..

add(Object o):- It adds the element in the end of the Vector.
 
elements():- It returns an enumeration of the element.

elementAt(int index):- It returns the element at the specified index.

firstElement():- It returns the first element of the vector.

lastElement():- It returns last element.

removeElementAt(int index):- It deletes the element from the given index.
 
size():- It returns total number of components available in vector.
import java.util.Vector;

public class VectorExample {
    public static void main(String[] args) {
        Vector<string> vector = new Vector<string>();
        vector.add("test1");
        vector.add("test2");
        vector.add("test3");
        vector.add("test4");
        vector.add("test5");
        // Print all the objects in vector
        System.out.println(vector);

        // Itreate all the objects in vector one by one
        for (String string : vector) {
            System.out.println("The value is " + string);
        }
        // Get object at index 4
        System.out.println("Object at index 4 is " + vector.get(4));

        // Get the size of a vector
        System.out.println("Size of vector is " + vector.size());

        // Get the array from list
        Object[] array = vector.toArray();
        System.out.println("The array of vector is " + array);
    }
}
Output is:

[test1, test2, test3, test4, test5]
The value is test1
The value is test2
The value is test3
The value is test4
The value is test5
Object at index 4 is test5
Size of vector is 5
The array of vector is [Ljava.lang.Object;@1372a1a

TreeSet and ArrayList

TreeSet implements SortedSet:- This class guarantees that the sorted set will be in ascending element order, sorted according to the natural order of the elements (see Comparable), or by the comparator provided at set creation time, depending on which constructor is used.
import java.util.Iterator;
import java.util.TreeSet;

public class TreeSetExample {

    public static void main(String[] args) {

        // TreeSet return in ordered elements
        TreeSet<String> ts=new TreeSet<String>();

        ts.add("b");
        ts.add("a");
        ts.add("d");
        ts.add("c");

        // get element in Iterator
        Iterator it=ts.iterator();

        // get descending order of elements
        //Iterator it=ts.descendingIterator();

        while(it.hasNext())
        {
          String value=(String)it.next();

          System.out.println("Value :"+value);
        }
    }
}
Output
TreeSet Value:a
TreeSet Value:b
TreeSet Value:c
TreeSet Value :d
 
ArrayList implements List Resizable:- Array implementation of the List interface. Implements all optional list operations, and permits all elements, including null. In addition to implementing the List interface, this class provides methods to manipulate the size of the array that is used internally to store the list.


import java.util.ArrayList;
public class SimpleArrayListExample {

 public static void main(String[] args) {

//create an ArrayList object
 ArrayList arrayList = new ArrayList();

/*
Add elements to Arraylist using
boolean add(Object o) method. It returns true as a general behavior
of Collection.add method. The specified object is appended at the end
of the ArrayList.
*/
 arrayList.add("1");
arrayList.add("2");
 arrayList.add("3");

/*
Use get method of Java ArrayList class to display elements of ArrayList.
 Object get(int index) returns and element at the specified index in the ArrayList   
*/
System.out.println("Getting elements of ArrayList");
System.out.println(arrayList.get(0));
System.out.println(arrayList.get(1));
System.out.println(arrayList.get(2));
}
}

/*
Output would be
Getting elements of ArrayList
1
2
1.3
*/

ArrayList class provides methods for basic array operations:- 

  • add( Object o ) - puts reference to object into ArrayList
  • get( int index ) - retrieves object reference from ArrayList index position
  • size() - returns ArrayList size
  • remove( int index ) - removes the element at the specified position in this list. Shifts any subsequent elements to the left and returns the element that was removed from the list.
  • indexOf( Object o) - finds the index in this list of the first occurrence of the specified element
  • clear() - removes all of the elements

HashSet and LinkedHashSet

HashSet implements Set:-
 
This class implements the Set interface, backed by a hash table (actually a HashMap instance). It makes no guarantees as to the iteration order of the set; in particular, it does not guarantee that the order will remain constant over time. This class permits the null element.

import java.util.*;
class HashSetDemo {
public static void main(String args[]) {
// create a hash set
HashSet hs = new HashSet();
// add elements to the hash set
hs.add("B");
hs.add("A");
hs.add("D");
hs.add("E");
hs.add("C");
hs.add("F");
System.out.println(hs);
}
}
The following is the output from this program:
[F, E, D, C, B, A]

LinkedHashSet extends HashSet implements Set:-

Hash table and linked list implementation of the Set interface, with predictable iteration order. This implementation differs from HashSet in that it maintains a doubly-linked list running through all of its entries. This linked list defines the iteration ordering, which is the order in which elements were inserted into the set (insertion-order). Note that insertion order is not affected if an element is re-inserted into the set.

import java.util.Iterator;
import java.util.LinkedHashSet;
import java.util.Set;

public class LinkedHashSetTest {

    public static void main(String[] args) {
        LinkedHashSet obj = new LinkedHashSet();

        obj.add("Hello234");
        obj.add("Hello454");
        obj.add("Hello564");

        Set e = obj;

        for (Iterator i = e.iterator(); i.hasNext();) {
            System.out.println(i.next().toString());

        }

    }
}

Running the code produces the following output:

Hello234
Hello454
Hello564
From the output it is clear the order in which you have added in the code has been output

Description of Collection Interfaces


The Collection Interfaces
This enables you to work with groups of objects; it is at the top of the collections hierarchy.
Lists:- Lists of things (classes that implement List).
 
Sets:-Unique things (classes that implement Set).
 
Queues:- Things arranged by the order in which they are to be processed.
Maps Things with a unique ID (classes that implement Map).

SortedSet extends Set :-This interface extends interface Set. A set that further guarantees that its iterator will traverse the set in ascending element order, sorted according to the natural ordering of its elements  or by a Comparator provided at sorted set creation time.

NavigableSet extends SortedSet:-The java.util.NavigableSet interface is a subtype of the java.util.SortedSet interface. It behaves like a SortedSet with the exception you have navigation methods available in addition to the sorting mechanisms of the SortedSet.we will look closer at the methods of the NavigableSet  interface later...

SortedMap extends Map:- A SortedMap is a map that maintains its entries in ascending order, sorted according to the keys' natural order, or according to a Comparator provided at SortedMap creation time

NavigaleMap extends SortedMap:-NavigableMap is similar to NavigableSet. In NavigableMap we use methods to return the key value pair like navMap.put(1, "January"); whereas in NavigableSet we use methods to return values.

Related Post:- Collection Classes

Share

Twitter Delicious Facebook Digg Stumbleupon Favorites More