Advertisement
MrDoyle

OOP) HashMaps Intro

Apr 14th, 2021
479
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 2.00 KB | None | 0 0
  1. import java.util.ArrayList;
  2. import java.util.HashMap;
  3.  
  4. public class Main {
  5.  
  6.     public static void main(String[] args) {
  7.  
  8.         //creatinga  new ArrayList object
  9.         ArrayList<Integer> test1 = new ArrayList<Integer>();
  10.  
  11.         //Using a Fir Loop to add values to th ArrayList
  12.        for (int i = 0 ; i < 5 ; i++){
  13.            test1.add(1);
  14.        }
  15.  
  16.        //Printing the ArrayList
  17.         for (int i = 0 ; i < 5 ; i++){
  18.             System.out.println(test1.get(i));
  19.         }
  20.  
  21.         //Using another For Loop to add more values to the ArrayList
  22.         for (int i = 0 ; i < 10 ; i++){
  23.             test1.add(2);
  24.         }
  25.  
  26.         //Using the .get() Method to get the size of the ArrayList
  27.         for (int i = 0 ; i < test1.size() ; i++){
  28.             System.out.println(test1.get(i));
  29.         }
  30.  
  31.         //Using a ForEach loop (A shortcut for writing a For Loop)
  32.         System.out.println("Before the For Each Loop");
  33.         for (Integer i : test1){
  34.             System.out.println(i);
  35.         }
  36.  
  37.  
  38.  
  39.         //Creating a new HashMap
  40.         System.out.println();
  41.         System.out.println("Testing HashMaps");
  42.         HashMap<String, Integer> studentGrades = new HashMap<String, Integer>();
  43.  
  44.         studentGrades.put("Mark",87);
  45.         studentGrades.put("Cassandra",95);
  46.         studentGrades.put("Zenas",64);
  47.  
  48.         System.out.println(studentGrades.get("Mark"));
  49.  
  50.         //using .size() to get the number of elements in the HashMap
  51.         System.out.println();
  52.         System.out.println("This is the current size of the HashMap: " + studentGrades.size());
  53.  
  54.         //Accessing the keys as data
  55.         System.out.println();
  56.         System.out.println("I am outputting all of the current keys in the HashMap: " + studentGrades.keySet());
  57.  
  58.         //Using the ForEach Loop for a HashMap
  59.         System.out.println();
  60.         for (String i:studentGrades.keySet()){
  61.             System.out.println(i + " has a grade of: " + studentGrades.get(i));
  62.         }
  63.  
  64.  
  65.     }
  66. }
  67.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement