Tuesday, September 16, 2025

Collection Framwork in java

 

Collection:- Any group of individual object which are represented as a single unit is know as the collection of the objects. 

Collection have two type:- 

       1. type safe - same type of element (object) are added to collection.

                        

                        ArrayList<String> name = new ArrayList<>();


ex:- It depends on the type - passing an integer instead of a string will cause an error.

        name.add("lakhan");

        name.add("harshi");

        name.add("thakur");

        name.add("Singh");

        name.add("Raj");


        2. un type safe - different types of elements can be added to collection.


                               LinkedList list = new LinkedList();

ex:- 

        list.add("Study"); // string

        list.add(123); // int

        list.add(45.6); // float

        list.add(true); //boolean

        list.add(101.5567); // double



Framework:- Is a set of Classes and Interface which provide a ready-made architecture.


                      Collection Framework 

Collection framework is a java API which is provide architecture to store and manipulate group of object.

Note:- 

Interface to interface :- extends
classes to interface :- implementation 
classes to classes :- extends

                       Collection Hierarchy



ListIterator:- Only use List family like ArrayList , LinkedList, Vector and Set family not allowed ListIterator.

List family allowed:- 

1. Indexed collection [0,1,2,3...]
2. Order is preserved
3. Duplicates are allowed.

Set family allowed:- 

1. Indexed  not collection [0,1,2,3...]
2. Order is  not preserved
3. Duplicates are not  allowed.

check below example.

Note:-

1. All collection methods are working for both (List and Set).
2. TreeSet and HashSet have no own methods it's using all collection methods.
3. check below example.

                               Code

      

package learn;


//import util package [all classes]


import java.util.*;


public class StartCode {

    public static void main(String[] args) {

        System.out.println("Welcome to java collection framework");



        /*

        * creating collection

        *

        * 1. type safe - same type of element (object) are added to collection.

        * 2. un type safe - different types of elements can be added to collection.

        *

        * */


        //type safe collection


        System.out.println("\ntype safe collection");


        ArrayList<String> name = new ArrayList<>();


        name.add("lakhan");

        name.add("harshi");

        name.add("thakur");

        name.add("Singh");

        name.add("Raj");

        System.out.println(name);


        //Indexed collection

        System.out.println(name.get(0)); // lakhan

        System.out.println(name.get(2)); //thakur


        //order is preserved

        System.out.println(name); // ['lakhan','hashi','thakur','singh','raj']


        //duplicate order are allowed

        name.add("Raj");

        System.out.println(name);//['lakhan','hashi','thakur','singh','raj','raj']



        //check item is there or not


        System.out.println("\ncheck item is there or not");

        System.out.println(name.contains("lakhan"));


        //check for empty


        System.out.println("\ncheck for empty");

        System.out.println(name.isEmpty());



        //untype safe collection

        System.out.println("\nuntype safe collection");


        LinkedList list = new LinkedList();


        list.add("Lakhan");

        list.add(123);

        list.add(45.6);

        list.add(true);

        list.add(101);


        System.out.println(list);



        //created the vector


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


        //add all collection(name is also a collection)

        vector.addAll(name);


        System.out.println("\nVectore;- "+vector);


           

        System.out.println("\n\n----------------SET Example----------------------");


        HashSet<Double> nms = new HashSet<>();


        nms.add(14.14);

        nms.add(34.12354);

        nms.add(2354.235);

        nms.add(99.3);

        nms.add(9.0);



        System.out.println(nms);//[14.14, 34.12354, 99.3, 2354.235]



        //set have no method it use a collection all methods


        //order is not preserved mean 99.3 not in index

        System.out.println(nms); // [14.14, 34.12354, 99.3, 2354.235]


        //duplicate order are not allowed

        nms.add(99.3);

        System.out.println(nms);//[14.14, 34.12354, 99.3, 2354.235]


        TreeSet<Double> tset = new TreeSet<>();


        System.out.println("\nTreeSet is sorted");

        tset.addAll(nms);

        System.out.println(tset);


    }

}


                        Traverse

List:- 

1. ListIterator
2. Iterator
3. for_each
4. foreach (Method)

Set:- 

1. Iterator
2. Iterable

Stack and Vector:- 

1. ListIterator
2. Iterator
3. for_each
4. foreach (Method)
                               

Code:- 

package learn;


import java.util.ArrayList;

import java.util.Iterator;

import java.util.ListIterator;

import java.util.TreeSet;


public class TraverseExample {

    public static void main(String[] args) {


        ArrayList<String> name = new ArrayList<>();

        name.add("lakhan");

        name.add("harshi");

        name.add("thakur");

        name.add("Singh");

        name.add("ABC");



        //for each loop:

        

        System.out.println("For each traverse\n");

        

        for (String str:name)

        {

            System.out.print(str + "\t" + str.length()+"\t");

            StringBuffer br = new StringBuffer(str);

            System.out.println(br.reverse());

        }


        System.out.println("_____________________");


        //traversing using ITERATOR : Forward traversing


        Iterator<String> itr = name.iterator();


        while(itr.hasNext())

        {

            String next = itr.next();

            System.out.println(next);

        }


        System.out.println("_____________________");


        //Backward traversal of collection LISTITERATOR


        System.out.println("Backward traversal of collection LISTITERATOR");


        ListIterator<String> litr = name.listIterator(name.size());

        

        while (litr.hasPrevious()){

            String previous = litr.previous();

            System.out.println(previous);

        }


        System.out.println("_____________________");


        //for each method (this is java 8 feature)


        System.out.println("\nFor each method (this is java 8 feature)\n");


        name.forEach(e->{

            System.out.println(e);

        });


        System.out.println("_____________________");


        //Tree set


        System.out.println("____________TREE SET SORTING OF ELEMENT_________");

        TreeSet<String> set = new TreeSet<>();


        set.addAll(name);

        

        set.forEach(str->{

            System.out.println(str);

        });


    }

}


Output:-


For each traverse


lakhan 6 nahkal

harshi 6 ihsrah

thakur 6 rukaht

Singh 5 hgniS

ABC 3 CBA

_____________________

lakhan

harshi

thakur

Singh

ABC

_____________________

Backward traversal of collection LISTITERATOR

ABC

Singh

thakur

harshi

lakhan

_____________________


For each method (this is java 8 feature)


lakhan

harshi

thakur

Singh

ABC

_____________________

____________TREE SET SORTING OF ELEMENT_________

ABC

Singh

harshi

lakhan

thakur


Process finished with exit code 0



                                   Map


Map:- it is used to store key-value pairs. Each key must be unique, but values can be duplicated.


  • Keys are unique (no duplicates allowed).
  • Each key maps to exactly one value.
  • Values can be duplicates.
Code:- 


package learn;


import java.util.HashMap;


public class MapExample {

    public static void main(String[] args) {

        

        HashMap<String, Integer> courses = new HashMap<>();


        //adding element


        courses.put("Core Java", 4000);

        courses.put("Basic Python", 3500);

        courses.put("Spring", 8000);

        courses.put("Android", 4000); //key duplicate

        courses.put("Android", 6000);

        courses.put("Php", 6000);

        System.out.println(courses);


        System.out.println("___________\n");

       courses.forEach((e1,e2)->{

           System.out.println(e1+ " => " +e2);

            //e1 is key and e2 is value

        });


        courses.forEach((key,value)->{

            System.out.print(key);

            System.out.print("=>");

            System.out.print(value);

            System.out.print("\n");

        });


        //get index of key

        System.out.println("_____Need to know the free of core java______\n");

        System.out.println(courses.get("Core Java"));

    }

}


output:-


{Core Java=4000, Php=6000, Basic Python=3500, Spring=8000, Android=6000}

___________


Core Java=>4000

Php=>6000

Basic Python=>3500

Spring=>8000

Android=>6000

_____Need to know the free of core java______


4000


                                Map vs. Set vs. List


Feature

List

Set

Map

Duplicates allowed?

Yes

No

Keys: No

Values: Yes

Stores key-value pairs?

No

No

Yes

Maintains order?

Yes

No (unless using TreeSet or LinkedHashSet)

No (unless using TreeMap or LinkedHashMap)


No comments:

Post a Comment

If you have any problem please let me know.