Showing posts with label Java Collections. Show all posts
Showing posts with label Java Collections. Show all posts

Thursday, 9 March 2017

The Map Interface

The Map Interface

A Map is an object that maps keys to values. A map cannot contain duplicate keys. Each key can map to at most one value.
 The Map interface includes methods for basic operations 
·         put 
·         get 
·         remove 
·         containsKey 
·         containsValue 
·         size 
·         empty

For Bulk operations 
·         putAll  
·         clear

For collection views 
·         keyset 
·         entrySet 
·         values

The Java platform provided three general purpose Map implementations 
·         HashMap 
·         TreeMap 
·         LinkedHashMap
Their behavior and performance are similar to HashSet, TreeSet, and LinkedHashSet.

Map Interface Basic Operations
import java.util.*;

public class MapDemo {
    public static void main(String[] args) {
        Map<String, Integer> m = new HashMap<String, Integer>();
        // Initialize frequency table from command line
        for (String a : args) {
            Integer freq = m.get(a);
            m.put(a, (freq == null) ? 1 : freq + 1);

        System.out.println(m.size() + " distinct words:");
Execute the above program using command line passing command line arguments
java MapDemo i came i saw i conquered

We will get  the following output.
4 distinct words:
{came=1, saw=1, conquered=1, i=3}

Replace the HashMap implementation with TreeMap implementation in the above code
Map<String, Integer> m = new HashMap<String, Integer>();
Map<String, Integer> m = new TreeMap<String, Integer>();
The output changes to
4 distinct words:
{came=1, conquered=1, i=3, saw=1}
In the output the words are now arranged in alphabetical order.
Map Interface Bulk Operations
·         The clear operation removes all the mappings from the Map.
·         The putAll operation is the Map similar of the Collection interface's addAll operation.
Collection Views
The Collection view methods allow a Map to be viewed as a Collection in three ways:
·         keySet  - the Set of keys contained in the Map.
·         values  -  The Collection of values contained in the Map.
·         entrySet — the Set of key-value pairs contained in the Map. The Map interface provides a small nested interface called Map.Entry, the type of the elements in this Set.
The Collection views provide the only means to iterate over a Map.

import java.util.*;
class HashMapDemo {
      public static void main(String args[]) {
//          Create a hash map
            HashMap hm = new HashMap();
            List l;
            //          Put elements to the map
            hm.put("John Doe", 3434.34);
            hm.put("Tom Smith", new Double(123.22));
            hm.put("Jane Baker", new Double(1378.00));
            hm.put("Todd Hall", new Double(99.22));
            hm.put("Ralph Smith", new Double(-19.08));
            hm.put("Ralph Smith", new Double(-9.08));
//          Get a set of the entries
            Set set = hm.entrySet();
//          Get an iterator
            Iterator i = set.iterator();
//          Display elements
            while(i.hasNext()) {
                  Map.Entry me = (Map.Entry);
                  System.out.print(me.getKey() + ": ");
//          Deposit 1000 into John Doe's account
            double balance = ((Double)hm.get("John Doe")).doubleValue();
            hm.put("John Doe", new Double(balance + 1000));
            System.out.println("John Doe's new balance: " +
                        hm.get("John Doe"));

Monday, 6 March 2017

The List Interface

The List Interface

List is an ordered Collection, sometimes called a sequence. Lists may contain duplicate elements. In addition to the operations inherited from Collection, the List interface includes operations for the following:
·         Positional access — manipulates elements based on their numerical position in the list. This includes methods such as get, set, add, addAll, and remove.
·         Search — searches for a specified object in the list and returns its numerical position. Search methods include indexOf and lastIndexOf.
·         Iteration — extends Iterator behaviour to take advantage of the list's sequential nature. The listIterator methods provide this behavior.
·         Range-view — The sublist method performs arbitrary range operations on the list.

The Java platform contains two general- purpose List implementations.
·         ArrayList, which is usually the better-performing implementation
·         LinkedList which offers better performance under certain circumstances.

ArrayList internally uses dynamic array to store the elements.
LinkedList internally uses doubly linked list to store the elements.
Manipulation with ArrayList is slow because it internally uses array. If any element is removed from the array, all the bits are shifted in memory.
Manipulation with LinkedList is faster than ArrayList because it uses doubly linked list so no bit shifting is required in memory.
ArrayList class can act as a list only because it implements List only.
LinkedList class can act as a list and queue both because it implements List and Deque interfaces.
ArrayList is better for storing and accessing data.
LinkedList is better for manipulating data.

Important methods of List Interface
Boolean add(Object obj)
Appends the specified element to the end of this list
void add(int index, Object obj)
Inserts the specified element at the specified position in this list
boolean addAll(int index, Collection c)
Inserts all elements of c into the invoking list at the index passed in the index. Returns true if the invoking list changes and returns false otherwise.
Object get(int index)
Returns the object stored at the specified index within the invoking collection.
int indexOf(Object obj)
Returns the index of the first occurrence of the specified element in this list, or -1 if this list does not contain the element.
int lastIndexOf(Object obj)
Returns the index of the last occurrence of the specified element in this list, or -1 if this list does not contain the element.
ListIterator listIterator( )
Returns an iterator to the start of the invoking list.
ListIterator listIterator(int index)
Returns an iterator to the invoking list that begins at the specified index.
Object remove(int index)
Removes the element at position index from the invoking list and returns the deleted element.
Object set(int index, Object obj)
Assigns obj to the location specified by index within the invoking list.
List subList(int start, int end)
Returns a view of the portion of this list between the specified fromIndex, inclusive, and toIndex, exclusive.

Sunday, 5 March 2017

The Set Interface

The Set Interface
A Set is a Collection that cannot contain duplicate elements. The Set interface contains only methods inherited from Collection and adds the restriction that duplicate elements are not added. 
The Java Platform contain three general purpose implementations of Set
·        HashSet 
·        TreeSet
·        LinkedHashSet

HashSet stores its elements in a hash table, and performance wise it is the best implementation. It makes no guarantees concerning the order of iteration.

TreeSet stores its elements in a tree structure, and the elements are orders based on their values. Its performance is slower than HashSet. 

LinkedHashSet is implemented as a hash table with a linked list running through it, orders its elements based on the order in which they were inserted into the Set. 

Set Interface Basic Operations

·        The add() method adds the specified element to the Set if it is not already present.
·        The remove() method removes the specified element from the Set if it is present.
·        The size() operation returns the number of elements in the Set. The isEmpty() method is used to check if this set contains no elements
·        The iterator() method returns an Iterator over the Set.

Set Interface Bulk Operations

Bulk operations are particularly well suited to Sets; when applied, they perform standard set-algebraic operations. Suppose s1 and s2 are sets. Here's what bulk operations do:
  • s1.containsAll(s2) — returns true if s2 is a subset of s1.
  • s1.addAll(s2) — transforms s1 into the union of s1 and s2.
  • s1.retainAll(s2) — transforms s1 into the intersection of s1 and s2.
  • s1.removeAll(s2) — transforms s1 into the set difference of s1 and s2.
Example of Set using HashSet and SortedSet

import java.util.*;
public class SetDemo {

  public static void main(String args[]) {
      int numbers[] = {34, 22,10,60,30,22};
      Set<Integer> set = new HashSet<Integer>();
      try {
         for(int i = 0; i < 5; i++) {
         System.out.println("Natural Set : ");

         TreeSet sortedSet = new TreeSet<Integer>(set);
         System.out.println("Sorted Set : ");
      catch(Exception e) {}

Related Posts Plugin for WordPress, Blogger...