Arrays & Collections
Sequences and key-value collections
Introduction
In this lesson, you'll learn about arrays & collections in Java. Coming from JavaScript, you already have a foundation for understanding this concept. We'll build on that knowledge while highlighting the key differences.
In JavaScript, you're familiar with sequences and key-value collections.
Java has its own approach to sequences and key-value collections, which we'll explore step by step.
The Java Way
Let's see how Java handles this concept. Here's a typical example:
import java.util.*;
import java.util.stream.*;
// ArrayList (dynamic array)
List<Integer> nums = new ArrayList<>(Arrays.asList(1, 2, 3));
nums.add(4);
// HashMap
Map<String, Integer> ages = new HashMap<>();
ages.put("Alice", 30);
ages.put("Bob", 25);
// Stream API — map/filter/reduce
List<Integer> doubled = nums.stream()
.map(n -> n * 2)
.collect(Collectors.toList());
List<Integer> evens = nums.stream()
.filter(n -> n % 2 == 0)
.collect(Collectors.toList());
int total = nums.stream()
.reduce(0, Integer::sum);Comparing to JavaScript
Here's how you might have written similar code in JavaScript:
// Dynamic array
const nums = [1, 2, 3];
nums.push(4);
// Map
const ages = new Map([["Alice", 30], ["Bob", 25]]);
ages.set("Charlie", 35);
// Functional
const doubled = nums.map(n => n * 2);
const evens = nums.filter(n => n % 2 === 0);
const total = nums.reduce((a, b) => a + b, 0);
// Destructuring
const [first, ...rest] = nums;You may be used to different syntax or behavior.
JS array → Java ArrayList<T> or LinkedList<T>
You may be used to different syntax or behavior.
JS Map → Java HashMap<K,V>
You may be used to different syntax or behavior.
Java Stream API replaces JS array .map/.filter/.reduce
You may be used to different syntax or behavior.
Java generics (List<Integer>) enforce element types
Step-by-Step Breakdown
1. ArrayList vs Array
Java arrays are fixed-size. ArrayList is the dynamic equivalent of a JS array — it grows as you add elements.
const nums = [1, 2, 3]; nums.push(4);List<Integer> nums = new ArrayList<>();
nums.add(1); nums.add(2); nums.add(4);2. HashMap
Java HashMap<K,V> is the equivalent of JS Map, but also of plain JS objects used as key-value stores.
const map = new Map(); map.set("key", 1);Map<String, Integer> map = new HashMap<>();
map.put("key", 1);
int val = map.get("key");3. Stream API
Java Streams provide map, filter, reduce, and more — the equivalent of JS array functional methods.
const total = nums.reduce((a, b) => a + b, 0);int total = nums.stream().reduce(0, Integer::sum);Common Mistakes
When coming from JavaScript, developers often make these mistakes:
- JS array → Java ArrayList<T> or LinkedList<T>
- JS Map → Java HashMap<K,V>
- Java Stream API replaces JS array .map/.filter/.reduce
Key Takeaways
- JS array → Java ArrayList<T>
- JS Map → Java HashMap<K,V>
- Java Stream API = JS .map/.filter/.reduce
- Java enforces element types with generics