CollectionFramework-Part-2 In Java



Iterators in Java

Iterator is used to iterator over collection of objects.
Iterator is interface.

package Test;
import java.util.ArrayList;
import java.util.Iterator;
public class Example2 {
           
      /**
     * Returns { true} if the iteration has more elements.
     * (In other words, returns {true} if {next} would
     * return an element rather than throwing an exception.)
     *
     * @return {@code true} if the iteration has more elements
     */
            public static void main(String[] args) {
                        ArrayList<Integer> array = new ArrayList<Integer>();
                        array.add(3);
                        array.add(4);
                        array.add(5);
                       
                        Iterator<Integer> itr = array.iterator();
                        while(itr.hasNext()){
                                    System.out.println(itr.next());
                        }
            }          
}
/*
Output: -
3
4
5
*/

Iterator Methods
·      boolean hasNext();
·      E next ();
·      void remove ();

boolean   hasNext()
·      Returns true if the iteration has more elements.

E    next ()
·      Returns the next element in the iteration.

void   remove ()
·      Removes from the underlying collection the last element returned by this iterator (optional operation).

boolean hasNext()
·      Returns true if the iteration has more elements. (In other words, returns true if next () would return an element rather than throwing an exception.)
·      Returns: true if the iteration has more elements

Methods in More Details:

E next ()
·      Returns the next element in the iteration.
·      Returns: the next element in the iteration
·      Throws:NoSuchElementException - if the iteration has no more elements

void remove ()
·      Removes from the underlying collection the last element returned by this iterator (optional operation). This method can be called only once per call to next ().
·      The behavior of an iterator is unspecified if the underlying collection is modified while the iteration is in progress in any way other than by calling this method.
·      Throws:UnsupportedOperationException - if the remove operation is not supported by this iterator.
·      IllegalStateException - if the next method has not yet been called, or the remove method has already been called after the last call to the next method.



Example2: Iterate over Linked List

package Test;
import java.util.Iterator;
import java.util.LinkedList;
import java.util.List;
public class Example2 {
            public static void main(String[] args) {
                        List<Integer> array = new LinkedList<Integer>();
                        array.add(3);
                        array.add(4);
                        array.add(5);
                       
                        Iterator<Integer> itr = array.iterator();
                        while(itr.hasNext()){
                                    System.out.println(itr.next());
                        }
            }          
}

List Iterator

It is used to Iterator over collection of object.

List Iterator Methods

boolean hasNext();
E next ();
boolean hasPrevious();
E previous ();
void remove ();


/**
 * Returns the previous element in the list and moves the cursor
 * position backwards.
*/
boolean hasPrevious();

/**
Return the previous element from list
*/
E previous();

/**
 * Returns the next element in the list and advances the cursor position.
 * This method may be called repeatedly to iterate through the list,
 */
boolean hasNext();

/**
 * Return the element for collection objects
 * @return
 */
E next();

void remove();

package Test;
import java.util.LinkedList;
import java.util.List;
import java.util.ListIterator;
public class Example2 {
            public static void main(String[] args) {
                       
                        List<Integer> array = new LinkedList<Integer>();
                        array.add(3);
                        array.add(42);
                        array.add(51);
                        array.add(50);
                        array.add(9);

                        ListIterator<Integer> itr = array.listIterator();
                        while(itr.hasNext()){
                                    System.out.println(itr.next());
                        }
                        System.out.println("Now we will get previous elements from last to first");
                        while(itr.hasPrevious()){
                                    System.out.println(itr.previous());
                        }
            }          
}

Output: -
3
42
51
50
9
Now we will get previous elements from last to first
9
50
51
42
3

package Test;
import java.util.LinkedList;
import java.util.List;
import java.util.ListIterator;
public class Example2 {
            public static void main(String[] args) {
                       
                        List<Integer> array = new LinkedList<Integer>();
                        array.add(3);
                        array.add(42);
                        array.add(51);
                        array.add(50);
                        array.add(9);
                       
        // listIterator() will give list of ListIterator
                        ListIterator<Integer> itr = array.listIterator();
                        // hasNext() will check the object in collection and move the pointer to next objects
                        while(itr.hasNext()){
                                    // itr.next() will return next element
                                    System.out.println(itr.next());
                        }
                        System.out.println("Now we will get previous elements from last to first");
                        // hasPrevious() will check the previous object from current point and move the
                        // Pointer to previous
                        while(itr.hasPrevious()){
                                    // itr.previous() will return previous element
                                    System.out.println(itr.previous());
                        }
                        // Once we reach to the previous elements, again we are Iterating
                        // And calling remove method. Remove method will return one by one
                        while(itr.hasNext()){
                                    // remove(); will remove object from collection of objects
                                    itr.remove();
                        }
            }          
}

Set in Java

Points to know:
1)    Set will store only unique data
2)    Hash Set will not maintain insertion order.

Methods and Constructors of Hash Set

Constructor
Description
HashSet()
It is used to construct a default HashSet.
HashSet(Collection c)
It is used to initialize the hash set by using the elements of the collection c.
HashSet(int capacity)
It is used to initialize the capacity of the hash set to the given integer value capacity. The capacity grows automatically as elements are added to the HashSet.
Methods of Java HashSet class:



Method
Description
boolean isEmpty()
It is used to return true if this set contains no elements.
boolean remove(Object o)
It is used to remove the specified element from this set if it is present.
Object clone()
It is used to return a shallow copy of this HashSet instance: the elements themselves are not cloned.
Iterator iterator()
It is used to return an iterator over the elements in this set.
int size()
It is used to return the number of elements in this set.
void clear()
It is used to remove all of the elements from this set.
boolean contains(Object o)
It is used to return true if this set contains the specified element.
boolean add(Object o)
It is used to adds the specified element to this set if it is not already present.


Example of Has Set

package Test;

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

public class ExampleHashSet {
           
            public static void main(String[] args) {
                        // Hash Set will store Only unique data.
                        Set<Integer> set = new HashSet<Integer>();
                        set.add(1);
                        set.add(1);
                        set.add(10);
                        set.add(7);
                        set.add(80);
                        set.add(8);
                        set.add(8);
                        // insertion order are not maintained
                        System.out.println(set);
            }
}
//output: [1, 80, 7, 8, 10]

Iterator on Hash Set

package Test;

import java.util.HashSet;
import java.util.Iterator;
import java.util.Set;

public class ExampleHashSet {
           
            public static void main(String[] args) {
                        // Hash Set will store Only unique data.
                        Set<Integer> set = new HashSet<Integer>();
                        set.add(1);
                        set.add(1);
                        set.add(10);
                        set.add(7);
                        set.add(80);
                        set.add(8);
                        set.add(8);
                        // insertion order are not maintained
                        // We can use iterator to iterate over the set, since get method is not supported.
                        // We cannot use set.get(0)
                        Iterator<Integer> itr = set.iterator();
                        while(itr.hasNext()){
                                    System.out.println(itr.next());
                        }
            }
}
//output
1
80
7
8
10

Linked Hash set will maintain insertion order.

package Test;

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

public class ExampleHashSet {
           
            public static void main(String[] args) {
                        Set<Integer> set = new LinkedHashSet<Integer>();
                        set.add(1);
                        set.add(1);
                        set.add(10);
                        set.add(7);
                        set.add(80);
                        set.add(8);
                        set.add(8);
                        System.out.println(set);
            }
}
//output: [1, 10, 7, 80, 8]

Tree Set Maintain the data in ascending order.

package Test;
import java.util.Set;
import java.util.TreeSet;

public class ExampleHashSet {
           
            public static void main(String[] args) {
                        Set<Integer> set = new TreeSet<Integer>();
                        set.add(1);
                        set.add(1);
                        set.add(10);
                        set.add(7);
                        set.add(80);
                        set.add(8);
                        set.add(8);
                        System.out.println(set);
            }
}
//output: [1, 7, 8, 10, 80]

Map in collection
·      Map will not maintain insertion order.
·      Map will store data based on key value pair
·      Map will store only unique data.
·       
Hash Map

·      A Hash Map contains values based on the key.
·      It contains only unique elements.
·      It may have one null key and multiple null values.
·      It maintains no order.

Constructors of Java Hash Map class

Constructor
Description
HashMap()
It is used to construct a default HashMap.
HashMap(Map m)
It is used to initializes the hash map by using the elements of the given Map object m.
HashMap(int capacity)
It is used to initializes the capacity of the hash map to the given integer value, capacity.
HashMap(int capacity, float fillRatio)
It is used to initialize both the capacity and fill ratio of the hash map by using its arguments.
Methods of Java Hash Map class

Method
Description
void clear()
It is used to remove all of the mappings from this map.
boolean containsKey(Object key)
It is used to return true if this map contains a mapping for the specified key.
boolean containsValue(Object value)
It is used to return true if this map maps one or more keys to the specified value.
boolean isEmpty()
It is used to return true if this map contains no key-value mappings.
Object clone()
It is used to return a shallow copy of this HashMap instance: the keys and values themselves are not cloned.
Set entrySet()
It is used to return a collection view of the mappings contained in this map.
Set keySet()
It is used to return a set view of the keys contained in this map.
Object put(Object key, Object value)
It is used to associate the specified value with the specified key in this map.
int size()
It is used to return the number of key-value mappings in this map.
Collection values()
It is used to return a collection view of the values contained in this map.

Example:
package Test;
import java.util.HashMap;
import java.util.Map;

public class ExampleHashSet {
           
            public static void main(String[] args) {
                        Map<Integer,Integer> map = new HashMap<Integer,Integer>();
                        map.put(1, 100);
                        map.put(20, 100);
                        map.put(30, 100);
                        map.put(4, 100);
                        System.out.println(map);
            }
}
//output: {1=100, 4=100, 20=100, 30=100}

Hash Map will store one null key.

package Test;
import java.util.HashMap;
import java.util.Map;

public class ExampleHashSet {
           
            public static void main(String[] args) {
                        Map<Integer,Integer> map = new HashMap<Integer,Integer>();
                        map.put(1, 100);
                        map.put(20, 100);
                        map.put(30, 100);
                        map.put(30, 100);
                        map.put(30, 100);
                        map.put(30, 100);
                        map.put(null, 100);
                        System.out.println(map);
            }
}
//output: {null=100, 1=100, 20=100, 30=100}




To get Data from Hash Map we have use method “get”
           
            /**
     * Returns the value to which the specified key is mapped,
     * or null if this map contains no mapping for the key.
     */
package Test;
import java.util.HashMap;
import java.util.Map;

public class ExampleHashSet {

            public static void main(String[] args) {
                        Map<Integer,Integer> map = new HashMap<Integer,Integer>();
                        map.put(1, 100);
                        map.put(20, 100);
                        map.put(30, 400);
                        map.put(30, 100);
                        map.put(30, 600);
                        map.put(30, 100);
                        map.put(null, 100);
                        System.out.println(map.get(1));
                        System.out.println(map.get(20));
                        System.out.println(map.get(30));
            }
}
//output:
100
100
100


Linked Hash Map will maintain insertion order

Example

package Test;
import java.util.LinkedHashMap;
import java.util.Map;

public class ExampleHashSet {
           
            public static void main(String[] args) {
                        Map<Integer,Integer> map = new LinkedHashMap<Integer,Integer>();
                        map.put(1, 100);
                        map.put(20, 100);
                        map.put(30, 100);
                        map.put(4, 100);
                        System.out.println(map);
            }
}
//output: {1=100, 20=100, 30=100, 4=100}

Tree Map will store the data in ascending order

package Test;
import java.util.Map;
import java.util.TreeMap;

public class ExampleHashSet {
           
            public static void main(String[] args) {
                        Map<Integer,Integer> map = new TreeMap<Integer,Integer>();
                        map.put(1, 100);
                        map.put(20, 100);
                        map.put(30, 100);
                        map.put(4, 100);
                        System.out.println(map);
            }
}
//output: {1=100, 4=100, 20=100, 30=100}
Hash Table

·      Hash Table is thread safe.
·      We cannot store null key in hash table
·      It will not insertion order.

Example

package Test;

import java.util.Hashtable;

public class HashTableInJava {
           
            public static void main(String[] args) {
                        Hashtable<Integer,Integer> obj = new Hashtable<Integer,Integer>();
                        obj.put(1, 900);
                        obj.put(2, 800);
                        obj.put(3, 600);
                        obj.put(4, 400);
                        obj.put(5, 900);
                        System.out.println(obj);
            }
}
// Output: - {5=900, 4=400, 3=600, 2=800, 1=900}

Comments

  1. Great Bhanu, its very informative and also I have seen your videos on Selenium Interview questions which helps us a lot.. Thanks a lot and waiting to get more info like this ..

    ReplyDelete
  2. The information about the Java framework is really much informative. Wish to learn Java from the basics to the advanced level, enroll you in Best Software Training Institute in Velachery to learn quickly...
    Java Training in Velachery | J2EE Training in Velachery

    ReplyDelete
  3. Your blog is really useful for me. Keep update your blog.
    Core Java Online Training Hyderabad

    ReplyDelete
  4. This blog awesome and i learn a lot about programming from here.The best thing about this blog is that you doing from beginning to experts level.

    Java Certification Course

    ReplyDelete
  5. This comment has been removed by the author.

    ReplyDelete
  6. Really informative blog.I got some valuable information from this.Keep posting
    Best Java Course

    ReplyDelete
  7. I am big fan of u sir, u are such a talented person. Thanks a lot.

    ReplyDelete
  8. I wish to show thanks to you just for bailing me out of this particular trouble.As a result of checking through the net and meeting techniques that were not productive, I thought my life was done.
    java training in chennai

    ReplyDelete
  9. explained it in a very nice way ..Keep posting such concepts

    ReplyDelete
  10. Great blog created by you. I read your blog, its best and useful information.
    Java training in chennai

    ReplyDelete
    Replies
    1. Hi,

      This is really great blog. It has complete information about Collection Framework. Thank you for sharing.

      Java Training in Chennai
      Java Course in Chennai

      Delete
  11. I am reading your post from the beginning, it was so interesting to read & I feel thanks to you for posting such a good blog, keep updates regularly..

    Java Training in Chennai | Java Training Institute in Chennai

    ReplyDelete
  12. It is a great article for Java. It is good for beginners. Thanks for sharing this great blog.
    Struts Training in Chennai | Struts Training

    ReplyDelete
  13. This comment has been removed by the author.

    ReplyDelete
  14. You have delivered the java in a incredible way.

    Java Training in chennai

    ReplyDelete
  15. Thank you for your information. It very nice article.
    Java Training in Pune

    ReplyDelete
  16. Very nice post, a bout Core Java ,thanks for posting java training

    ReplyDelete
  17. informative post. so good. learned more about java. thank u for sharing. Best java training in chennai

    ReplyDelete
  18. Good Post! Thank you so much for sharing this pretty post, it was so good to read and useful to improve my knowledge as updated one, keep blogging.

    https://www.emexotechnologies.com/courses/other-technology-trainings/python-training

    https://www.emexotechnologies.com/courses/big-data-analytics-training/data-science-with-python-training

    https://www.emexotechnologies.com/courses/cloud-computing-training/amazon-web-services-aws-training

    https://www.emexotechnologies.com/courses/big-data-analytics-training/big-data-hadoop-training

    https://www.emexotechnologies.com/courses/other-technology-trainings/devops-training

    ReplyDelete
  19. Your new valuable key points imply much a person like me and extremely more to my office workers. With thanks; from every one of us.
    Click here:
    Online training in USA

    ReplyDelete

  20. The post is very much informative. Pls do update more. You can also visit our website Java Training in Chennai | Java course in Chennai | Java Training Institute in Chennai
    for more information.

    ReplyDelete
  21. I have read your blog its very attractive and impressive. I like your blog core Java online course

    ReplyDelete
  22. Thank you for benefiting from time to focus on this kind of, I feel firmly about it and also really like comprehending far more with this particular subject matter. In case doable, when you get know-how, is it possible to thoughts modernizing your site together with far more details? It’s extremely useful to me 
    python interview questions and answers | python tutorialspython course institute in electronic city

    ReplyDelete
  23. Very informative article, thank you.
    For most common java interview programs visit:
    Java programming

    ReplyDelete
  24. I found your blog while searching for the updates, I am happy to be here. Very useful content and also easily understandable providing.. Believe me I did wrote an post about tutorials for beginners with reference of your blog. 
    excel advanced excel training in bangalore

    ReplyDelete
  25. You got an extremely helpful website I actually have been here reading for regarding an hour. I’m an initiate and your success is incredibly a lot of a concept on behalf of me.
    angularjs Training in bangalore

    angularjs Training in btm

    angularjs Training in electronic-city

    angularjs online Training

    angularjs Training in marathahalli

    angularjs interview questions and answers

    ReplyDelete
  26. "very nice and amazing blog you have written i have read all this blog many things mentioned in this blog please keep updating the blog and posting because Dot net is a very easy and simple language. it is easy to understand and use and also support multiple languages.
    Dot Net training in Chandigarh
    Data Science training Chandigarh
    Big data training Mohali"

    ReplyDelete
  27. Good article for the java beginners. Java is vast and learning java programming is continues process, for that blog reading is very good one.
    https://www.exltech.in/java-training.html

    ReplyDelete
  28. Hey, would you mind if I share your blog with my twitter group? There’s a lot of folks that I think would enjoy your content. Please let me know. Thank you.
    Java Training in Chennai | J2EE Training in Chennai | Advanced Java Training in Chennai | Core Java Training in Chennai | Java Training institute in Chennai

    ReplyDelete
  29. It’s great to come across a blog every once in a while that isn’t the same out of date rehashed material. Fantastic read.Surya Informatics

    ReplyDelete
  30. Good Post! Thank you so much for sharing the nice post, it was so good to read and useful to improve
    Java Training in Electronic City

    ReplyDelete


  31. the blog is really great and thanks for sharing oracle training in chennai

    ReplyDelete
  32. Really Helpful Content about Frame work Collection. Keep Posting.
    Get started with your Java training by learning the basics of Java programming language and what is core java and Features of Java Programming Language with our free video tutorials in Hindi.


    ReplyDelete
  33. I feel really happy to have seen your webpage and look forward to so many more entertaining times reading here. Thanks once more for all the details.


    linen sarees
    silk cotton sarees
    dhoti for men
    silk shirts for men
    designer silk sarees

    ReplyDelete
  34. This is great stuff!! need to share lots of articles for the reader who like your blog and thanks for sharing your ideas and tips
    1Z0-809: Java SE 8 Programmer II

    ReplyDelete
  35. Waoo This interview question is so amazing,this is very helpful.
    This site is so amazing, This sites gives good knowledge of core java ,This is very helpful for me. Here all content so useful and helpful for beginner and experience both.

    ReplyDelete
  36. インド人ITエンジニアを活用して、ウェブとアプリ含めシステム開発サービスを提供しています。

    アプリ 開発 オフショア

    ReplyDelete
  37. Thanks a lot for sharing it here with us.
    Well, I have also seen this post https://www.techgeekbuzz.com/blog/core-java-interview-questions/ where author listed almost 100 core java basic questions with detailed information about it including coding examples.
    Thanks

    ReplyDelete

  38. Nice! This is the great post I like this post and thanks for share to me. eCareerpluz provide IT Skill Programs like Beginner Level Courses, Programming Courses, etc…
    Best Java Training in Madurai | Best C/C++ Training in Madurai | Best Python Training in Madurai | Basic Computer Course | Best Tally Training in Madurai
    https://careerpluz.in/java-training-madurai

    ReplyDelete
  39. amazing post, thanks for sharing this information. Full Stack Classes In Pune

    ReplyDelete

Post a Comment

Popular posts from this blog

OOPs concepts In Java