Friday, 9 June 2017

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


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:

CLICK HERE

No comments:

Post a Comment