Java - Data structure - Map

Hashtable

Key and Value date format

Can not be null

Sync-ed


HashMap

Key and Value date format

Can be null

Non sync so will be faster


Methods : 

put

remove (will return reomved item of null)

get (by Key)

keySet (return all Keys)


Need to using iterator to loop the elements

eg:

Iterator<Integer> itr = hashtable.keySet().iterator();
while (itr.hasNext()) {
Integer key = itr.next();
String value = hashtable.get(key);
System.out.println("Key" + key + " ,Value = " + value);
}

Or
for(Map.Entry<String,String> m : hsMap.entrySet()){
    System.out.println(m.getKey() + m.getValue());
}

Eg :  map and stream to find the max value
Map<Integer , Integer> map = new HashMap<>();

        
        for(int i = 0 ; i < nums.length;i++){               //3 
            if (map.putIfAbsent(nums[i] , 1) != null){// ture = first time, 
                int count = map.get(nums[i]);
                map.replace(nums[i],count += 1);
            }
        }

        int max =  map.entrySet().stream()
                        .max(Comparator.comparing(Map.Entry::getValue))
                        .orElse(null).getKey();

留言

此網誌的熱門文章

MAP - Sort with stream

JAVA - DSF Example