Tuesday, 26 March 2013

How to read and write value in List,Map,Set using getter and setter method in java

import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.Set;
import java.util.TreeSet;
import java.util.*;


public class CollectionEG
{

private Set setv;
private List listv;
private Map<String,String> mapv;


public Set getSetv() {
    return setv;
}
public void setSetv(Set setv) {
    this.setv = setv;
}
public List getListv() {
    return listv;
}
public void setListv(List listv) {
    this.listv = listv;
}
public Map<String, String> getMapv() {
    return mapv;
}
public void setMapv(Map<String, String> mapv) {
    this.mapv = mapv;
}

public static void main(String args[])
{
    CollectionEG cd=new CollectionEG();


    //This example for Map
    Map<String,String> map=new HashMap<String,String>();

        map.put("one","1");
        map.put("two","2");
        map.put("three","3");

        cd.setMapv(map);
        map=null;
        map=cd.getMapv();


        Set s=map.entrySet();
        Iterator mapIterator = s.iterator();
        System.out.println("Map Demo");
        while(mapIterator.hasNext())
        {
            Map.Entry mapEntry = (Map.Entry) mapIterator.next();
            // getKey Method of HashMap access a key of map
            String keyValue = (String) mapEntry.getKey();
            //getValue method returns corresponding key's value
            String value = (String) mapEntry.getValue();
            System.out.println("Key : " + keyValue + "= Value : " + value);

        }



    //This example for List
    System.out.println("List Demo");
    List list=new ArrayList<Integer>();
    list.add(1);
    list.add(2);
    cd.setListv(list);

    list=null;
    list=cd.getListv();
    for(int i=0;i<list.size();i++)
    {
        System.out.println(list.get(i));
    }


    //This example for Set
    System.out.println("Set Demo");
      Set<Integer> set = new TreeSet<Integer>();

    set.add(1);
    set.add(2);
    set.add(3);

    cd.setSetv(set);

    set=null;
    set=cd.getSetv();

    Iterator<Integer> iterator = set.iterator();
    while(iterator.hasNext())
    {
        Integer setElement = iterator.next();
        System.out.println(setElement);
    }

  }
}

No comments:

Post a Comment