Member-only story

From Python To Java (Part 5) — Dictionaries (Python) VS HashMaps (Java)

Liu Zuo Lin
3 min readJan 2, 2022

--

This series of articles is written for those of you who are somewhat comfortable in Python, and are looking to pick up some Java. In this article, we’ll run through dictionaries (Python) and the equivalent in Java, which are HashMaps

Creating A Dictionary/HashMap

Python Dictionary

d = {"apple": 4, "orange": 5, "pear":6}

Pretty straightforward in Python

Java HashMap

As usual, we first need to import the HashMap class.

import java.util.HashMap;

Put this at the top of your java class below the package definition.

HashMap<String, Integer> map = new HashMap<>();
map.put("apple", 4);
map.put("orange", 5);
map.put("pear", 6);

If we print map, we get:

{orange=5, apple=4, pear=6}

Here, notice the <String, Integer> portion of the code. We are essentially telling Java that keys in the HashMap will all be strings, and values in the HashMap will all be integers.

Note: Like ArrayLists, a class needs to go between the < and > arrows, so we need to use Integer instead of int to represent integers.

--

--

Liu Zuo Lin
Liu Zuo Lin

Written by Liu Zuo Lin

SWE @ Meta | [Ebook] 101 Things I Never Knew About Python: https://payhip.com/b/vywcf

No responses yet