PY
JV

Python to Java

11 lessons

Progress0%
1Introduction2Variables & Types3Functions to Methods4Lists to Arrays5Dicts to Maps6Classes & OOP7Inheritance8Exception Handling9Modules to Packages10Ecosystem11Modern Java Features
All Mirror Courses
PY
JV
Dicts to Maps
MirrorLesson 5 of 11
Lesson 5

Dicts to Maps

Dicts to Maps

Introduction

In this lesson, you'll learn about dicts to maps in Java. Coming from Python, you already have a foundation for understanding this concept. We'll build on that knowledge while highlighting the key differences.

Mirror Card
PY
From Python:

In Python, you're familiar with dicts to maps.

JV
In Java:

Java has its own approach to dicts to maps, which we'll explore step by step.

The Java Way

Let's see how Java handles this concept. Here's a typical example:

JV
Java Example
import java.util.*;
import java.util.stream.*;

Map<String, Object> person = new HashMap<>();
person.put("name", "Alice");
person.put("age", 30);

// Access
System.out.println(person.get("name"));
System.out.println(person.getOrDefault("city", "Unknown"));

// Iterate
for (Map.Entry<String, Object> e : person.entrySet()) {
    System.out.println(e.getKey() + " " + e.getValue());
}

// Collectors.toMap (dict comprehension equivalent)
Map<Integer, Integer> squares = IntStream.range(0, 5)
    .boxed()
    .collect(Collectors.toMap(n -> n, n -> n * n));

Comparing to Python

Here's how you might have written similar code in Python:

PY
Python (What you know)
person = {"name": "Alice", "age": 30}

# Access
print(person.get("name"))
print(person.get("city", "Unknown"))

# Iterate
for key, val in person.items():
    print(key, val)

# Dict comprehension
squares = {n: n**2 for n in range(5)}
Mirror Card
PY
From Python:

You may be used to different syntax or behavior.

JV
In Java:

Python dict literal {k: v} vs Java HashMap constructor + .put()

Mirror Card
PY
From Python:

You may be used to different syntax or behavior.

JV
In Java:

Python .get(k, default) → Java .getOrDefault(k, default)

Mirror Card
PY
From Python:

You may be used to different syntax or behavior.

JV
In Java:

Python .items() → Java .entrySet() returning Map.Entry objects

Mirror Card
PY
From Python:

You may be used to different syntax or behavior.

JV
In Java:

Java HashMap is type-safe — Map<String, Integer> enforces key/value types

Mirror Card
PY
From Python:

You may be used to different syntax or behavior.

JV
In Java:

Dict comprehension → Collectors.toMap() with Streams

Step-by-Step Breakdown

1. Creating and Populating

Java has no map literal syntax. Create a HashMap and call .put() for each entry.

PY
Python
person = {"name": "Alice", "age": 30}
JV
Java
Map<String, Object> person = new HashMap<>();
person.put("name", "Alice");
person.put("age", 30);
Rule of Thumb
Use Map.of("k1", v1, "k2", v2) for small immutable maps (Java 9+).

2. Safe Access with Default

.getOrDefault(key, fallback) is Java's equivalent of Python's .get(key, default).

PY
Python
city = person.get("city", "Unknown")
JV
Java
String city = (String) person.getOrDefault("city", "Unknown");

3. Iterating Entries

.entrySet() returns a Set of Map.Entry objects, each with .getKey() and .getValue().

PY
Python
for key, val in person.items():
    print(key, val)
JV
Java
for (Map.Entry<String, Object> e : person.entrySet()) {
    System.out.println(e.getKey() + " " + e.getValue());
}

4. Dict Comprehension → Collectors.toMap

Use IntStream or a stream with Collectors.toMap() to build a map from a range or collection.

PY
Python
squares = {n: n**2 for n in range(5)}
JV
Java
Map<Integer, Integer> squares = IntStream.range(0, 5)
    .boxed()
    .collect(Collectors.toMap(n -> n, n -> n * n));
Common Pitfall
Collectors.toMap throws on duplicate keys by default. Provide a merge function as the third argument if duplicates are possible.

Common Mistakes

When coming from Python, developers often make these mistakes:

  • Python dict literal {k: v} vs Java HashMap constructor + .put()
  • Python .get(k, default) → Java .getOrDefault(k, default)
  • Python .items() → Java .entrySet() returning Map.Entry objects
Common Pitfall
Don't assume Java works exactly like Python. While the concepts may be similar, the syntax and behavior can differ significantly.

Key Takeaways

  • HashMap + .put() replaces dict literal syntax
  • .getOrDefault(k, v) ≈ dict.get(k, default)
  • .entrySet() ≈ dict.items()
Rule of Thumb
The best way to learn is by doing. Try rewriting some of your Python code in Java to practice these concepts.
PreviousNext