java4all@1986 java. Powered by Blogger.
Showing posts with label Collections. Show all posts
Showing posts with label Collections. Show all posts

Methods of Map.entry Interface?

>> Monday, May 30, 2011

Map.Entry is an Interface ,it consists of  some methods.
   public  Object getKey(){};
  public Object getValue(){};

These methods can be used to get key and value fro a map;

Sample program:
import java.util.Iterator;
import java.util.Map;
import java.util.Properties;

public class Main {
  public static void main(String[] a) {
    Properties props = System.getProperties();
    Iterator iter = props.entrySet().iterator();

    while (iter.hasNext()) {
      Map.Entry entry = (Map.Entry) iter.next();
      System.out.println(entry.getKey() + " -- " + entry.getValue());
    }

  }
}

OUTPUT::
sun.cpu.endian -- little
sun.desktop -- windows
sun.cpu.isalist --
 The output we got from system property files.

Read more...

How to create HashTable from HashMap?




import java.util.Enumeration;
import java.util.HashMap;
import java.util.Hashtable;

public class Main {
  public static void main(String[] args) {

    HashMap hMap = new HashMap();

    hMap.put("1", "One");
    hMap.put("2", "Two");
    hMap.put("3", "Three");

    Hashtable ht = new Hashtable();
    ht.put("1", "REPLACED !!");
    ht.put("4", "Four");

    Enumeration e = ht.elements();
    while (e.hasMoreElements()){
      System.out.println(e.nextElement());
         }      

    ht.putAll(hMap);
    e = ht.elements();
System.out.println("in hashtable");
    while (e.hasMoreElements()){
    
     System.out.println(e.nextElement());
    }      
    
  }
}
 
OUTPUT:
Four
REPLACED !!
in hashtable
Four
Three
Two
One

Read more...

What are the advantages of collection Framework?

Advantages: Collections framework provides flexibility, performance,
and robustness.

Polymorphic algorithms – sorting, shuffling, reversing, binary search etc.
1.) Set algebra - such as finding subsets, intersections, and unions between objects.
 2.)Performance - collections have much better performance compared to the older Vector and Hashtable classes with
the elimination of synchronization overheads.
 3.)Thread-safety - when synchronization is required, wrapper implementations are provided for temporarily
4.)synchronizing existing collection objects. For J2SE 5.0 use java.util.concurrent package.
 Immutability - when immutability is required wrapper implementations are provided for making a collection
immutable.
5.) Extensibility - interfaces and abstract classes provide an excellent starting point for adding functionality and
features to create specialized object collections

Read more...

Difference between Iterator,ListIterator and Enumeratio?

Iterator:It is an interface, which can be used to iterate objects in forward Direction.
     Following are the methods of Iterator,
     1.)public boolean hasNext(){};
      2.)public object next(){};
       3.)public void remove(){};

ListIterator:It is an interface ,which can be used to iterate objects in forward direction as well as in Backward direction.
          Following are the methods of ListIterator,
        1.)public boolean hasNext(){};
      2.)public object next(){};
       3.)public void remove(){};
       4.)public boolean hasPerivous(){};
       5.)public object perivous(){};

Enumeration: It is an interface which can be used to iterate objects in forward direction.But it doesn't havr a method to remove object.
        Following are the methods of Enumeration,
      1.)public boolean hasMoreElement(){};
       2.)public object nextElement(){};

Read more...

Difference Between Comparable and Comparator Interface?

Comparable interface:
1.The “Comparable” allows itself to compare with another
similar object (i.e. A class that implements Comparable
becomes an object to be compared with). The method
compareTo() is specified in the interface.
2.Many of the standard classes in the Java library like String,
Integer, Date, File etc implement the Comparable interface
to give the class a "Natural Ordering". For example String
class uses the following methods:
3.public int compareTo(o)
public int compareToIgnoreCase(str)
4.
public class Pet implements Comparable {
int petId;
String petType;
public Pet(int argPetId, String argPetType) {
petId = argPetId;
this.petType = argPetType;
}
public int compareTo(Object o) {
Pet petAnother = (Pet)o;
//natural alphabetical ordering by type
//if equal returns 0, if greater returns +ve int,
//if less returns -ve int
return this.petType.compareTo(petAnother.petType);
}
public static void main(String[] args) {
List list = new ArrayList();
list.add(new Pet(2, "Dog"));
list.add(new Pet(1, "Parrot"));
list.add(new Pet(2, "Cat"));
Collections.sort(list); // sorts using compareTo method
for (Iterator iter = list.iterator(); iter.hasNext();) {
Pet element = (Pet) iter.next();
System.out.println(element);
}
}
public String toString() {
return petType;
}
}
Output: Cat, Dog, Parrot
Comparator interface:
1.The Comparator is used to compare two different objects. The
following method is specified in the Comparator interface.
public int compare(Object o1, Object o2)
2.You can have more control by writing your Comparator class. Let us
write a Comparator for the Pet class shown on the left. For most cases
natural ordering is fine as shown on the left but say we require a
special scenario where we need to first sort by the “petId” and then by
the “petType”. We can achieve this by writing a “Comparator” class.
3.
public class PetComparator implements Comparator, Serializable{
public int compare(Object o1, Object o2) {
int result = 0;
Pet pet = (Pet)o1;
Pet petAnother = (Pet)o2;
//use Integer class's natural ordering
Integer pId = new Integer(pet.getPetId());
Integer pAnotherId = new Integer(petAnother.getPetId());
result = pId.compareTo(pAnotherId);
//if ids are same compare by petType
if(result == 0) {
result= pet.getPetType().compareTo
(petAnother.getPetType());
}
return result;
}
public static void main(String[] args) {
List list = new ArrayList();
list.add(new Pet(2, "Dog"));
list.add(new Pet(1, "Parrot"));
list.add(new Pet(2, "Cat"));
Collections.sort(list, new PetComparator());
for (Iterator iter = list.iterator(); iter.hasNext();){
Pet element = (Pet) iter.next();
System.out.println(element);
}
}
}
Output: Parrot, Cat, Dog.

Read more...

How to itreate objects in Map?

>> Thursday, May 26, 2011

Map: It can be used to store group of objects in the of name value pairs.

package com.centris.atr.bean;

import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import java.util.Set;

public class IterateMap {
     public static void main(String[] args) {
        Map m=new HashMap();
        m.put(1, "bhaskar");
        m.put(2,"Ajantha");
        m.put(3, "prathap");
        Set s=m.entrySet();
        Iterator it =s.iterator();
        while(it.hasNext())
        {
            System.out.println(it.next());
        }
    }

}

Read more...

Important Points in Collections

>> Tuesday, May 24, 2011

To know Collections concept completely  and clearly follow the below steps.
1.Heterogeneous Objects:
                (a)TreeSet and TreeMap doesn't allow Heterogeneous Objects.
2.Insertion Order:
                (b)Only List & it's child Classes ,LinkedHaset ,LinkedHashMap preserved.
3.Duplicate Values: 
                (c)Only List and it's child Classes allow......In Map values are allowed.
4.Display Order:
                (d)For TreeMap and TreeSet as per sorting order.

 5.Null Acceptance:
                (e)HashTable, TreeSet,TreeMap doesn't allow.
6.Synchronized:
                 (f)Vector,Stack,HashTable,properties are Synchronized.

7.Default Sizes:
                  (g)List and Child Classes=10
                      Set and it's child Classes=16 
                      Map & it's child Classes=16.
8.Incermental size/Ratio: 
                    (h)List and it's child Classes=16
                         Set & Map=0.75(loadFactor,fillRatio) 

Read more...

To get duplicate key we use Identity HashMap with Example?

To identify duplicate keys in Identity HasMap JVM uses (==).

PROGRAM:
                  class DuplcateKeys{
                    IdentityHashMap ihm=new IdentityHashMap();
                   ihm.put("10", "BHaskar");
                   ihm.put("10","Ajantha");
                    System.out.println(ihm);
                              }
OUTPUT:
          {10 : Bhaskar,  10:Ajantha}

Read more...

To identify duplicate keys in HasMap?Example

1.To identify duplicate keys in HasMap JVM internally uses equals() Method.
                          
         PROGRAM:
                                class DuplicateKey
                                 {
                                   HashMap hm=new HashMap();
                                   hm.put("10","Bhaskar");
                                   hm.put("10","Ajantha");
                                   System.out.println(hm);
                                          }
                      OUTPUT :
                                      {10 , Ajantha}         

In HashMap  it overrides the duplicate    key of it's values.












Read more...

Get Synchronized Map from Java HashMap ?

import java.util.Collections;
import java.util.HashMap;
import java.util.Map;

public class Main {
  public static void main(String[] args) {
    HashMap hashMap = new HashMap();
    Map map = Collections.synchronizedMap(hashMap);
  }
}

Read more...

Search with a Comparator

import java.util.Arrays;
import java.util.Comparator;

public class AlphabeticSearch {

  public static void main(String[] args) {
    String[] sa = new String[] { "a""c""d" };
    AlphabeticComparator comp = new AlphabeticComparator();
    Arrays.sort(sa, comp);
    int index = Arrays.binarySearch(sa, sa[10], comp);
    System.out.println("Index = " + index);
  }
///:~

class AlphabeticComparator implements Comparator {
  public int compare(Object o1, Object o2) {
    String s1 = (Stringo1;
    String s2 = (Stringo2;
    return s1.toLowerCase().compareTo(s2.toLowerCase());
  }
///:~

Read more...

Reverse Order Comparator

import java.util.Comparator;
public class ReverseOrder<T> implements Comparator<T>
{
    private Comparator<T> m_comparator;
    
    public ReverseOrder(Comparator<T> comp)
    {
        m_comparator = comp;
    }

public int compare(T arg0, T arg1)
    {
        return -* m_comparator.compare(arg0, arg1);
    }
}

Read more...

Creating a Comparable object

import java.util.Arrays;
import java.util.Set;
import java.util.TreeSet;

public class Person implements Comparable {
  String firstName, lastName;

  public Person(String f, String l) {
    this.firstName = f;
    this.lastName = l;
  }

  public String getFirstName() {
    return firstName;
  }

  public String getLastName() {
    return lastName;
  }

  public String toString() {
    return "[dept=" + firstName + ",name=" + lastName + "]";
  }

  public int compareTo(Object obj) {
    Person emp = (Personobj;
    int deptComp = firstName.compareTo(emp.getFirstName());

    return ((deptComp == 0? lastName.compareTo(emp.getLastName())
        : deptComp);
  }

  public boolean equals(Object obj) {
    if (!(obj instanceof Person)) {
      return false;
    }
    Person emp = (Personobj;
    return firstName.equals(emp.getFirstName())
        && lastName.equals(emp.getLastName());
  }

  public static void main(String args[]) {
    Person emps[] new Person("Debbie""Degree"),
        new Person("Geri""Grade")new Person("Ester""Extent"),
        new Person("Mary""Measure"),
        new Person("Anastasia""Amount") };
    Set set = new TreeSet(Arrays.asList(emps));
    System.out.println(set);
  }
}
           
        

Read more...

Your own auto-growth Array

public class Array implements java.util.Enumeration,java.io.Serializable
{
    private int current = 0;
    private int size = 10;
    private int grow = 2;
    private int place = 0;
    private Object[] elements = null;
    private Object[] tmpElements = null;

    public Array()
    {
        init();
    }

    public Array(int size)
    {
        setSize(size);
        init();
    }

    public Array(int size,int grow)
    {
        setSize(size);
        setGrow(grow);
        init();
    }

    private void init()
    {
        elements = new Object[size];
    }

    public Object nextElement() throws java.util.NoSuchElementException
    {
        if elements[place!= null && place != current)
        {
            place++;
            return elements[place - 1];
        }
        else
        {
            place = 0;
            throw new java.util.NoSuchElementException();
        }
    }

    public boolean hasMoreElements()
    {
        ifplace < elements.length && current != place )
            return true;
        return false;
    }

    public void setSize(int size)
    {
        this.size = size;
    }

    public int getCurrentSize()
    {
        return current;
    }

    public void rehash()
    {
        tmpElements = new Object[size];
        int count = 0;
        for int x = 0; x < elements.length; x++ )
        {
            ifelements[x!= null )
            {
                tmpElements[count= elements[x];
                count++;
            }
        }
        elements = (Object[])tmpElements.clone();
        tmpElements = null;
        current = count;
    }

    public void setGrow(int grow)
    {
        this.grow = grow;
    }

    public void grow()
    {
        size = size+=(size/grow);
        rehash();
    }

    public void add(Object o)
    {
        ifcurrent == elements.length )
            grow();

        try
        {
            elements[current= o;
            current++;
        }
        catch(java.lang.ArrayStoreException ase)
        {
        }
    }

    public void add(int location,Object o)
    {
        try
        {
            elements[location= o;
        }
        catch(java.lang.ArrayStoreException ase)
        {
        }
    }

    public void remove(int location)
    {
        elements[locationnull;
    }

    public int location(Object othrows NoSuchObjectException
    {
        int loc = -1;
        for int x = 0; x < elements.length; x++ )
        {
            if((elements[x!= null && elements[x== o )||
               (elements[x!= null && elements[x].equals(o)))
            {
                loc = x;
                break;
            }
        }
        ifloc == -)
            throw new NoSuchObjectException();
        return(loc);
    }

    public Object get(int location)
    {
        return elements[location];
    }

    public java.util.Enumeration elements()
    {
        return this;
    }
}
class NoSuchObjectException extends Exception
{

    public NoSuchObjectException()
    {
        super("No such object found.");
    }
}

Read more...

Copy Elements of ArrayList to Java Vector

import java.util.ArrayList;
import java.util.Collections;
import java.util.Vector;

public class Main {
  public static void main(String[] args) {
    ArrayList<String> arrayList = new ArrayList<String>();

    arrayList.add("1");
    arrayList.add("2");
    arrayList.add("3");
    arrayList.add("4");
    arrayList.add("5");

    Vector<String> v = new Vector<String>();

    v.add("A");
    v.add("B");
    v.add("D");
    v.add("E");
    v.add("F");
    v.add("G");
    v.add("H");

    System.out.println(v);
    Collections.copy(v, arrayList);
    System.out.println(v);
  }
}


output:
[A, B, D, E, F, G, H]
[1, 2, 3, 4, 5, G, H]

Read more...

Get Enumeration over Java ArrayList

import java.util.ArrayList;
import java.util.Collections;
import java.util.Enumeration;

public class Main {
  public static void main(String[] args) {
    ArrayList<String> arrayList = new ArrayList<String>();

    arrayList.add("A");
    arrayList.add("B");
    arrayList.add("D");
    arrayList.add("E");
    arrayList.add("F");

    Enumeration e = Collections.enumeration(arrayList);

    while (e.hasMoreElements())
      System.out.println(e.nextElement());
  }
}

Read more...

Get Enumeration over Java ArrayList

import java.util.ArrayList;
import java.util.Collections;
import java.util.Enumeration;

public class Main {
  public static void main(String[] args) {
    ArrayList<String> arrayList = new ArrayList<String>();

    arrayList.add("A");
    arrayList.add("B");
    arrayList.add("D");
    arrayList.add("E");
    arrayList.add("F");

    Enumeration e = Collections.enumeration(arrayList);

    while (e.hasMoreElements())
      System.out.println(e.nextElement());
  }
}

Read more...

Find maximum element of HashSet

>> Monday, May 23, 2011

import java.util.Collections;
import java.util.HashSet;

public class Main {

public static void main(String[] args) {
HashSet hashSet = new HashSet();
hashSet.add(new Long("1111111111"));
hashSet.add(new Long("2222222222"));
hashSet.add(new Long("3333333333"));
hashSet.add(new Long("4444444444"));
hashSet.add(new Long("5555555555"));

Object obj = Collections.max(hashSet);
System.out.println(obj);
}
}

Read more...

An easy way to initialize a set without manually adding each element

import java.util.Arrays;
import java.util.HashSet;
import java.util.Set;

public class MainClass {

public static void main(String[] a) {
String elements[] = { "A", "B", "C", "D", "E" };
Set set = new HashSet(Arrays.asList(elements));

System.out.println(set);

}

}

Read more...

Remove duplicate items from an ArrayList

import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;

public class Main {
public static void main(String[] argv) {
List arrayList1 = new ArrayList();

arrayList1.add("A");
arrayList1.add("A");
arrayList1.add("B");
arrayList1.add("B");
arrayList1.add("B");
arrayList1.add("C");

HashSet hashSet = new HashSet(arrayList1);

List arrayList2 = new ArrayList(hashSet);

for (Object item : arrayList2)
System.out.println(item);
}
}

Read more...

FaceBook Login

HTML/JAVASCRIPT

HTML/JAVASCRIPT

HTML/JAVASCRIPT

HTML/JAVASCRIPT

Total Pageviews

STATCOUNTER

  © Blogger template Simple n' Sweet by Ourblogtemplates.com 2009

Back to TOP