Thursday, 15 October 2015

JAVA : COLLECTION Tips

1. Check Duplicate in collection.



2. Want to add objects in order



3. SORT HASHTABLE -> JUST CONVERT HASHTABLE TO TREEMAP (Automatically will be sorted)

public static void main (String[] args) {
Hashtable<String, String> ht= new Hashtable<String, String>();
       ht.put("zac", "Chaitanya");
       ht.put("abc", "Ajeet");
       ht.put("yyt", "Test");
       ht.put("ddc", "Demo");
       ht.put("ssa", "Anuj");

    Map<String, String> map = new TreeMap<String, String>(ht);
    for(Map.Entry<String,String> entry : map.entrySet()) {
          String key = entry.getKey();
          String value = entry.getValue();
        
          System.out.println(key + " => " + value);
    }

OR

    Map hm = new TreeMap(ht);
    Set<String> keys = hm.keySet();
        for(String key: keys){
            System.out.println("Value of "+key+" is: "+hm.get(key));
        }


}

No comments:

Post a Comment