Learn/Java/7. Collections
Lesson 7 of 15
Sign in

Java, lesson 7

Collections

One variable holds one value. To work with a whole shopping list, a week of temperatures or a phone book, you need a collection. Java gives you three workhorses: arrays, lists and maps.

Arrays: a fixed row of values

An array has a fixed length and one element type. Indexes start at 0:

Reading scores[3] here throws an ArrayIndexOutOfBoundsException: the last valid index is always length - 1. You have already used an array: split returns a String[].

ArrayList: a list that grows

When you do not know the size in advance, use ArrayList from java.util:

2 exercises to try what you just read.

Exercise 1

Weekly temperatures

Press Ctrl Enter or Check to test your code.

Exercise 2

Phone book

Press Ctrl Enter or Check to test your code.

The type in angle brackets, <String>, says what the list holds. It is called a type argument, and the empty <> on the right lets Java fill it in for you. Declaring the variable as List (the interface) rather than ArrayList (one implementation) is the usual style.

Collections cannot hold primitives directly, so a list of numbers is List<Integer>, using the wrapper class Integer. Java converts between int and Integer automatically (autoboxing), so you can still write numbers.add(5).

List.of("a", "b", "c") creates a small unmodifiable list in one line. It is great for fixed data, but calling add on it throws an exception.

The for-each loop

To visit every element in order, use the enhanced for loop. It works for arrays and for every collection:

Read it as "for each s in scores". Use an index-based for only when you need the position.

HashMap: look values up by key

A map stores key–value pairs, like a dictionary stores words and definitions. Each key appears at most once:

Loop over a map's pairs with entrySet():

A HashMap does not keep any particular order. If you need keys sorted, use a TreeMap; if you need insertion order, use a LinkedHashMap. They work the same way otherwise.

Further reading

  • Arrays (dev.java)
  • Storing elements in lists (dev.java)
  • Using maps (dev.java)
  • ArrayList API

The input is one line of whole-number temperatures separated by spaces (at least one). Print the lowest, the highest, the average with one decimal place, and how many days were strictly warmer than the average.

Sample input:

Sample output:

The first line is a number N. The next N lines each hold a name and a phone number separated by a space. Every line after that is a name to look up. For each lookup, print the number, or Not found if the name is not in the book. Names are case sensitive.

Sample input:

Sample output:

int[] scores = {12, 7, 30};
System.out.println(scores[0]);       // 12
scores[1] = 8;                       // replace an element
System.out.println(scores.length);   // 3

double[] prices = new double[5];     // five zeros, filled in later
import java.util.ArrayList;
import java.util.List;

List<String> cart = new ArrayList<>();
cart.add("apples");
cart.add("bread");
cart.add(0, "milk");           // insert at the front
System.out.println(cart);      // [milk, apples, bread]
System.out.println(cart.get(1));   // apples
cart.remove("bread");
System.out.println(cart.size());   // 2
System.out.println(cart.contains("milk")); // true
int total = 0;
for (int s : scores) {
    total += s;
}
import java.util.HashMap;
import java.util.Map;

Map<String, Integer> stock = new HashMap<>();
stock.put("apple", 12);
stock.put("pear", 4);
stock.put("apple", 10);                  // replaces the old value
System.out.println(stock.get("apple"));  // 10
System.out.println(stock.get("kiwi"));   // null: no such key
System.out.println(stock.getOrDefault("kiwi", 0)); // 0
System.out.println(stock.containsKey("pear"));     // true
for (Map.Entry<String, Integer> e : stock.entrySet()) {
    System.out.println(e.getKey() + ": " + e.getValue());
}
12 15 9 20 18 11 14
Min: 9
Max: 20
Average: 14.1
Above average: 3
3
alice 555-1234
bob 555-9876
carol 555-2468
bob
dave
alice
555-9876
Not found
555-1234