Monday, 15 May 2017

Java Tutorial: Generics in java | Java Generics [Generics example using List, Set and Map]


Click here to watch in Youtube : 
https://www.youtube.com/watch?v=QqHZHE-fUec&list=UUhwKlOVR041tngjerWxVccw

GenericForDemo1.java
import java.util.ArrayList;
import java.util.List;

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

        List<String> list = new ArrayList<String>();
        list.add("Peter");
        list.add("Juli");
        list.add("Stephan");

        /*
         * Java's Generic For Loop or for each loop.
         */
        for (String aString : list)
        {
            System.out.println(aString);
        }

    }

}
Output
Peter
Juli
Stephan
GenericForDemo2.java
import java.util.HashSet;
import java.util.Set;

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

        Set<Integer> set = new HashSet<Integer>();
        set.add(100);
        set.add(200);
        set.add(300);

        /*
         * Java's Generic For Loop or for each loop.
         */
        for (Integer integerValue : set)
        {
            System.out.println(integerValue);
        }

    }

}
Output
100
200
300
GenericForDemo3.java
import java.util.HashMap;
import java.util.Map;

public class GenericForDemo3
{
    public static void main(String[] args)
    {
        Map<Integer, String> map = new HashMap<Integer, String>();
        map.put(1, "Ram");
        map.put(2, "Peter");
        map.put(3, "Juli");

        /*
         * Java's Generic For Loop or for each loop.
         */
        for (Integer key : map.keySet())
        {
            String value = map.get(key);
            System.out.println("" + key + ":" + value);
        }

        System.out.println("-------------------------------");

        /*
         * Java's Generic For Loop or for each loop.
         */
        for (String value : map.values())
        {
            System.out.println(value);
        }
    }

}
Output
1:Ram
2:Peter
3:Juli
-------------------------------
Ram
Peter
Juli
Click the below link to download the code:
https://sites.google.com/site/ramj2eev1/home/javabasics/GenericsDemo_List_Set_Map_App.zip?attredirects=0&d=1

Github Link:
https://github.com/ramram43210/Java/tree/master/BasicJava/GenericsDemo_List_Set_Map_App

Bitbucket Link:
https://bitbucket.org/ramram43210/java/src/47d09ebb24294f7b507419345f38ec4cde27d544/BasicJava/GenericsDemo_List_Set_Map_App/?at=master

See also:
  • All JavaEE Viedos Playlist
  • All JavaEE Viedos
  • All JAVA EE Links
  • Servlets Tutorial
  • All Design Patterns Links
  • JDBC Tutorial
  • Java Collection Framework Tutorial
  • JAVA Tutorial
  • Kids Tutorial
  • No comments:

    Post a Comment