Monday, 23 July 2018

JAVA : COLLECTION Tips

JAVA : COLLECTION Tips


Note : HashSet and TreeSet is used to resolve many scenarios (Remove duplicate, find duplicate, sort Array, find Min/Max number in array etc...)

1. Check Duplicate in collection.



2. Want to add objects in order



3. Want to find highest and lowest number in non-sorted array.

1> First add it to TreeSet
2> treeset.first() -> 1
     treeset.last() -> 8

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