Powered by Blogger.
Showing posts with label Collections. Show all posts
Showing posts with label Collections. Show all posts

java.util.HashMap in detail with a program

>> Friday, September 12, 2014

HashMap is a class from java.util package and extends AbstractMap, implements Map,Cloneable and Serializable interfaces. HashMap contains Key,Value parameters we can denote it as HashMap<Key,Value> or HashMap<k,v>.Map allows only one null key and many null values and all the methods in HashMap are not synchronized. HashMap is an unordered collection , means the keys and values will not maintain insertion order.
An instance of HashMap has two parameters that affect its performance: initial capacity and load factor.
Let us know the terminology used in HashMap.

Read more..

How to Iterate or Traverse a Map in Java

>> Sunday, June 22, 2014

Iterating a Map is not like a List Iteration. Map is having key-value pair to store the elements. Based on key,we can retrieve mapped value.To Iterate or loop a map we have 3 ways using with the help of Map.Entry, keySet() and entrySet()methods.
How to Iterate or Traverse a Map_Javabynataraj
Explanation about Map.Entry,keySet() and entrySet()

Read more..

When to use ensureCapacity method in java

>> Sunday, January 5, 2014

In java Colleciton framework ArrayList and Vector classes contains ensureCapacity(int minCapacity) method to reduce or manage the amount of incremental memory allocation.
When to use ensureCapacity method in java_javabynataraj
Each ArrayList instance has a capacity. The capacity is the size of the array used to store the elements in the list. It is always at least as large as the list size. As elements are added to an ArrayList, its capacity grows automatically.

An application can increase the capacity of an ArrayList instance before adding a large number of elements using the ensureCapacity operation. This may reduce the amount of incremental reallocation.

Read more..

How to sort an ArrayList

>> Tuesday, October 2, 2012

Sorting any ArrayList is pretty simple. Using Collections.sort( ) method we can sort the ArrayList. Collections class having all the static methods, we can use those methods directly along with the class name. These methods return the object as type Collection.

The important methods to synchronize the List, Set and Map as

synchronizedList(List<T> list)
synchronizedSet(Set<T> s)
synchronizedMap(Map<K,V> m) 

A simple program to sort an ArrayList

Read more..

How to Iterate Generic type of ArrayList

>> Sunday, June 10, 2012

Generics in Java
Generics were introduced in Java 1.5 to define abstract types for the variables of by enclosing a comma-separated list of their names within angle brackets after the name of the class or interface. We can user this type of variables any where in the class if a type is required in any instance fields or methods of the class.

Now in this post we are learning how to iterate the Generic type of list.

Normally we used to iterate any list we take the help of Iterator. If it is normal list as well we can iterate the Generic type.

Lets take a bean class of User with a constructor and setters and getters methods.

Here the User having the String type name and link variables.

Read more..

Understanding foreach loop in Java

>> Sunday, January 8, 2012


To make iteration over arrays and other collections more convenient Java5 extended the basic for loop and it is named as for-each Loop and also called as enhanced for loop or foreach loop.

The for-each loop is used to access each successive value in a collection of values.

This foreach loop is commonly used to iterate over an array or a Collections class (eg, ArrayList).

Read more..

What is the difference between Iterator and Listiterator ?

>> Saturday, August 20, 2011


There are two Differences are there :

1. We can use Iterator to traverse Set and List and also Map type of Objects. But List Iterator can be used to traverse for List type Objects, but not for Set type of Objects.

That is, we can get a Iterrator object by using Set and List, see here :

 By using Iterator we can retrieve the elements from Collection Object in forward direction only.

Methods in Iterator :

1. hashNext()
2. next()
3. remove()



Iterator ite = Set.iterator();
Iterator ite = List.iterator();

Read more..

Can i convert List to Set (or) ArrayList to HashSet ?

>> Friday, June 10, 2011

Yes.We can convert from List to Set.Both are under the same Superclass Collection Interface.So there are more chances to convert.







Actually ArrayList follows the insertion order of elements.When you tried to convert from ArrayList to HashSet it won't preserve the previous order, it may change according to the properties of HashSet.Set won't maintain the order of elements.

Here we are passing the reference of the List to HashSet constructor at the creation of set object.

Set<Object> set = new HashSet<Object>(list);

Read more..

Can i convert Set into List ?

Yes.we can convert a Set into List.The List and Set both are interfaces having superclass of Collection interface.

Create an object of HashSet which is implemented a Set Interface.Add the objects to the HashSet using add() method.


Set<String> set = new HashSet<String>();
  set.add("username");
  set.add("password");
  set.add("login");

And same Create an object of ArrayList which is implemented a List Interface.Pass the reference object of Set while creating the ArrayList object.

List<String> list = new ArrayList<String>(set);

Read more..

How to Iterate Map using Generics

>> Thursday, June 9, 2011

Map is an interface.We can iterate the implemented classes from map like TreeMap,HashMap,LinkedHashMap.

Maps do not provide an iterator() method as do Lists and Sets. A Set of either keys (keySet()) or key-value 'Map.Entry' elements (entrySet()) can be obtained from the Map, and one can iterate over that.

Create an object for HashMap and insert the objects in that.

Map<Integer, String> map = new HashMap<Integer, String>();
  map.put(100, "Murali");
  map.put(200, "khaleel");
  map.put(300, "Bhaskar");

Read more..

Collections KeyPoints

>> Thursday, May 19, 2011

The Main Collections KeyPoints in java

Collection is a group of objects.  java.util package provides important types of collections. There are two fundamental types of collections they are Collection and Map. Collection types hold a group of objects, Eg. Lists and Sets where as Map types hold group of objects as key, value pairs.
Eg. Hashtable, HashMap, TreeMap, and LinkedHashMap (LinkedList+HashTable). Explained in detail in last post, how to iterate HashMap.
Here the collections of classes and interfaces having some their own properties.They are


Read more..

Example to find maxmimum element in a Vector

>> Sunday, October 17, 2010

Example to find maximum element in a Vector

This java example shows how to find a maximum element of Java Vector using max method of Collections class.To find maximum element of Java Vector use, static Object max(Collection c) method of Collections class.

This method returns the maximum element of Java Vector according to its natural ordering.

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

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

     //create a Vector object
     Vector v = new Vector();
     //Add elements to Vector
 
     v.add(new Double("324.4324"));
     v.add(new Double("345.3532"));
     v.add(new Double("342.342"));
     v.add(new Double("357.349"));
      v.add(new Double("23.32453"));

      Object obj = Collections.max(v);
     System.out.println("Maximum Element of Java Vector is : " + obj);

     }
    }


The Output is:

Maximum Element of Java Vector is : 357.349

Reference Books:

Read more..

Example to Find maxmimum element in ArrayList

Example to Find maxmimum element in ArrayList

This java example shows how to find a maximum element of Java ArrayList using max method of Collections class.

To find maximum element of Java ArrayList use, static Object max(Collection c) method of Collections class.
This method returns the maximum element of Java ArrayList according to its natural ordering.

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

    public class FindMaximumOfArrayListExample {

     public static void main(String[] args) {

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

     //Add elements to Arraylist
     arrayList.add(new Integer("327482"));
     arrayList.add(new Integer("13408"));
     arrayList.add(new Integer("802348"));
     arrayList.add(new Integer("345308"));
     arrayList.add(new Integer("509324"));

     Object obj = Collections.max(arrayList);
     System.out.println("Maximum Element of Java ArrayList is : " + obj);

     }
    }

The Output :

Maximum Element of Java ArrayList is : 802348

Reference Books: 

Read more..

Create a List containing n Copies of Specified Object

Create a List containing n Copies of Specified Object This java example shows how to create a list consisting n copies of specified copies using nCopies method of Collections class.

To create a List containing n copies of specified Object use static List nCopies(int n, Object obj) method of Java Collection class.This method returns immutable List containing n copies of the specified Object.
List Containing N copies of Specified Object_JavabynataraJ

Read more..

Enumerate Vector using java.util.Enumeration

Enumerate through a Vector using Java Enumeration Example.This Java Example shows how to enumerate through elements of a Vector using Java Enumeration.

Enumeration provides two methods to enumerate through the elements. It's hasMoreElements method returns true if there are more elements to enumerate through otherwise it returns false. Its nextElement method returns the next element in enumeration.

static ArrayList list(Enumeration e) method of Collections class. This method returns the ArrayList containing the elements returned by specified Enumeration object in order they are returned.

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

   public class CreateArrayListFromEnumerationExample {
   public static void main(String[] args) {
   //create a Vector object
   Vector v = new Vector();
   //Add elements to Vector

   v.add("A");
   v.add("B");
   v.add("D");
   v.add("E");
   v.add("F");
   
   System.out.println("Vector contains : " + v);
   //Get Enumeration over Vector
   Enumeration e = v.elements();
   //Create ArrayList from Enumeration of Vector
   ArrayList aList = Collections.list(e);
   System.out.println("Arraylist contains : " + aList);

  }
 }

Output is:

Vector Contains : [A, B, D, E, F]
Arraylist contains : [A, B, D, E, F]

Reference Books:

Read more..

Copy Elements of Vector to Java ArrayList Example

  1. /*
  2. Copy Elements of Vector to Java ArrayList Example
  3. This java example shows how to copy elements of Java Vector to Java ArrayList using
  4. copy method of Collections class.
  5. */
  6. import java.util.ArrayList;
  7. import java.util.Collections;
  8. import java.util.Vector;
  9. public class CopyElementsOfVectorToArrayListExample {
  10. public static void main(String[] args) {
  11. //create a Vector object
  12. Vector v = new Vector();
  13. //Add elements to Vector
  14. v.add("1");
  15. v.add("2");
  16. v.add("3");
  17. //create an ArrayList object
  18. ArrayList arrayList = new ArrayList();
  19. //Add elements to Arraylist
  20. arrayList.add("One");
  21. arrayList.add("Two");
  22. arrayList.add("Three");
  23. arrayList.add("Four");
  24. arrayList.add("Five");
  25. /*
  26. To copy elements of Java Vector to Java ArrayList use,
  27. static void copy(List dstList, List sourceList) method of Collections class.
  28. This method copies all elements of source list to destination list. After copy
  29. index of the elements in both source and destination lists would be identical.
  30. The destination list must be long enough to hold all copied elements. If it is
  31. longer than that, the rest of the destination list's elments would remain
  32. unaffected.
  33. */
  34. System.out.println("Before copy ArrayList Contains : " + arrayList);
  35. //copy all elements of Vector to ArrayList using copy method of Collections class
  36. Collections.copy(arrayList,v);
  37. /*
  38. Please note that, If ArrayList is not long enough to hold all elements of
  39. Vector, it throws IndexOutOfBoundsException.
  40. */
  41. System.out.println("After Copy ArrayList Contains : " + arrayList);
  42. }
  43. }
  44. /*
  45. Output would be
  46. Before copy ArrayList Contains : [One, Two, Three, Four, Five]
  47. After Copy ArrayList Contains : [1, 2, 3, Four, Five]
  48. */

Read more..

Copy Objects from One Vector to Another Vector using Java

Copy Elements of One Java Vector to Another Java Vector Example

This java example shows how to copy all elements of one Java Vector object to
another Java Vector object using copy method of Collections class.

Read more..

Copy Elements of ArrayList to Vector Example

Copying ArrayList elements from Vector is so simple by using predefined method in Collections class.
Collections.copy(vector,arrayList);
Java Collections_ArrayList to Vector Example_JavabynataraJ
/*This java example shows how to copy elements of Java ArrayList to Java Vector using
copy method of Collections class.
*/

Read more..

Copy Elements from one ArrayList to Another ArrayList

Here is the Program to copy the values from one ArrayList to another ArrayList.

package collect;

import java.util.ArrayList;
import java.util.Collections;
import java.util.Iterator;
import java.util.List;


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

  List l1=new ArrayList(); 
  
  l1.add("hi");
  l1.add("brother");
  
  ArrayList al=new ArrayList(); 
  al.add("hello");  
  al.add("guru");   
  
  Collections.copy(al,l1);   
  Iterator i= al.iterator();  
  
  while(i.hasNext()){ 
   i.hasNext();  
   System.out.print(" "+i.next()); 
   //System.out.println(al);  
  }   
 }  
}

This is the procedure to copying the objects from one list to another.

For Java References:
Effective Java (2nd Edition) 

Read more..

Collections Hirarchy

>> Friday, May 28, 2010

 
Collections Hirarchy diagram

Read more..

Related Posts Plugin for WordPress, Blogger...
© javabynataraj.blogspot.com from 2009 - 2022. All rights reserved.