Maps Example

Subscribe to Tech With Tim!

Maps Example

Here is a practical example of when we would use a map. Try to figure out what the following code does. Watch the video if you'd like the answer.

import java.util.*;

public class Main{
	public static void main(String[] args){
		Map m = new HashMap();
		String str = "Hello my name is tim and I am cool";

		for(char x: str.toCharArray()){
			if (m.containsKey(x)){
				int count = (int)m.get(x);
				m.put(x, count+1);
			}
			else{
				m.put(x, 1);
			}
		}
		m.remove(' ');

		System.out.println(m);
	}
}