LoganBlackisle

HashMap

Jun 18th, 2019
53
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 0.88 KB | None | 0 0
  1. package prep_31_hashing;
  2.  
  3. import java.util.HashMap;
  4. import java.util.Map;
  5.  
  6. public class HashMaps {
  7. public static void createHashMap(int arr[]) {
  8. // Creates an empty HashMap
  9. Map<Integer, Integer> hmap = new HashMap<Integer, Integer>();
  10.  
  11. // Traverse through the given array
  12. for (int i = 0; i < arr.length; i++) {
  13.  
  14. // Get if the element is present
  15. Integer c = hmap.get(arr[i]);
  16.  
  17. // If this is first occurrence of element
  18. // Insert the element
  19. if (hmap.get(arr[i]) == null) {
  20. hmap.put(arr[i], 1);
  21. }
  22.  
  23. // If elements already exists in hash map
  24. // Increment the count of element by 1
  25. else {
  26. hmap.put(arr[i], ++c);
  27. }
  28. }
  29.  
  30. // Print HashMap
  31. System.out.println(hmap);
  32. }
  33.  
  34. // Driver method to test above method
  35. public static void main(String[] args) {
  36. int arr[] = { 10, 34, 5, 10, 3, 5, 10 };
  37. createHashMap(arr);
  38. }
  39. }
Add Comment
Please, Sign In to add comment