Skip to content
Code To Live By » Java Tutorial » Collections in Java

Collections in Java

  • by

We discussed Variables which allow us to store values, but what if we wanted to store multiple values? There are a number of ways to do this in Java, each suited for different purposes.

Arrays

Arrays are probably the most basic way to do this. For semantics’ sake an Array is not a “Collection” under the Java Collection hierarchy but we are grouping it here because they are both used for storing multiple values.

Let’s say we wanted to store numbers one through five. We could initialize such an array like this:

int[] numbers = new int[5];

Now we have an empty integer array with 5 five elements.

Then in order to populate elements in our array, we can refer to them by their “index.” In Computer Science indexes begin at zero and increment from there. So in our example to fill our array with numbers one through five we would see:

numbers[0] = 1;
numbers[1] = 2;
numbers[2] = 3;
numbers[3] = 4;
numbers[4] = 5;

Alternatively we could declare and initialize our array like this:

int[] numbers = {1,2,3,4,5};

We can also access elements of the array by their index. So in our example if we wanted to get the middle element of our array we can access it with the index 2.

numbers[2]; // 3

We can also use the foreach loop we discussed in our page on Loops to print the entire array easily.

int[] numbers = {1,2,3,4,5};
for (int number : numbers) {
	System.out.println(number);
}

Our output in this case would look like this:

1
2
3
4
5

There are however some things that can make using arrays a little unwieldy. Arrays are a fixed size so if we wanted to add or remove elements to our array we would need to create an entirely new array. This however can be addressed by “Lists”

Lists

A List is another way in which we can store multiple values. In contrast to arrays Lists are dynamically sized, so we don’t need to decide its size on initialization. We will specifically be looking at the ArrayList.

We would first need to add the following imports to our program

import java.util.ArrayList;
import java.util.List;

Then we can create a List with numbers 1-5 with something like this:

List<Integer> list = new ArrayList<>();
list.add(1);
list.add(2);
list.add(3);
list.add(4);
list.add(5);

One additional thing to note is that Lists cannot hold primitive types. So in our case of wanting to create a List with number we cannot use the primitive int we discussed from Variables, but we can use Integer which is a wrapper class around the primitive Int.

We could also initialize Lists using the asList() method from java.util.Arrays

import java.util.Arrays;
import java.util.List;

// ...

List<Integer> numbers = Arrays.asList(1,2,3,4,5);

We can then access elements of the List by using the get() method with its index of the List that we want. So getting the middle element of the List would look something like this:

numbers.get(2); //3

Similar to arrays, we can use the foreach to print the entire List.

for (Integer number : numbers) {
	System.out.println(number);
}

Map

In contrast to Arrays and Lists which allow storing an ordered sequence of elements, a Map allows us to store a “key value pairs.” Many other languages refer to this concept as a “dictionary.”

Lets say we wanted to store the ASCII codes for alphabetic characters. We can declare a Map in a similar way that we can declare a List

import java.util.HashMap;
import java.util.Map;

// ...

Map<String, Integer> asciiCodes = new HashMap<>();

Then we can begin adding out key value pairs by using the put method with our desired key and value

asciiCodes.put("A", 65);
asciiCodes.put("B", 66);
asciiCodes.put("C", 67);
asciiCodes.put("D", 68);
asciiCodes.put("E", 69);

In order to retrieve values we can use the get method on our Map and pass our key as a parameter.

asciiCodes.get("C");

If we wanted to print out the entirety of our Map we can do so by using a foreach loop on the set of the Map’s keys

for (String key : asciiCodes.keySet()) {
	System.out.println(key + ": " + asciiCodes.get(key));
}

This would give us the following output:

A: 65
B: 66
C: 67
D: 68
E: 69

Multi Dimensional Collections

You can also create Arrays / Collections within Arrays / Collections to create “multi dimensional” Arrays / collections.

Let’s say we wanted to represent some sort of grid or coordinate system. We would have an X axis as well as a Y axis. We could represent both axis as a List, resulting in a two dimensional “grid.” We could create this grid with something like this:

List<List<Integer>> coordinates = new ArrayList<>();
for (int y = 0; y < 5; y++) {
	coordinates.add(new ArrayList<>());
	for (int x = 0; x < 5; x++) {
		coordinates.get(y).add(x);
	}
}

You may remember nested loops our page on Loops. In this example we are looping over our y and x axes and populating with our grid. As this is an example we are literally just using coordinates themselves as the values but you could store whatever else here. Then if we wanted to loop through again to print out this grid we might use something like this:

for (int y = 0; y < coordinates.size(); y++) {
	for (int x = 0; x < coordinates.get(y).size(); x++) {
		System.out.print("(" + coordinates.get(y).get(x) + ", " + y + ") ");
	}
	System.out.print("\n");
}

This loops over our y and x axes again to give us the following output :

(0, 0) (1, 0) (2, 0) (3, 0) (4, 0) 
(0, 1) (1, 1) (2, 1) (3, 1) (4, 1) 
(0, 2) (1, 2) (2, 2) (3, 2) (4, 2) 
(0, 3) (1, 3) (2, 3) (3, 3) (4, 3) 
(0, 4) (1, 4) (2, 4) (3, 4) (4, 4) 

Other

There are of course numerous other collections that you can use if you so choose. Like much of this tutorial, I want to focus primarily on the things that I think are going to be the most useful in practical development. However, I also believe in using the right tool for the job, so in this case I will briefly touch on some of the more theoretical types that may still have niche uses.

Set

A Set is an unordered collection that does not allow duplicate elements.

Queue

A Queue is a “First In First Out” Collection, similar to the line (or queue if you’re European) to checkout your groceries. Elements can only be added to the start of the queue and removed from the end of the queue. You will be tutted for trying to insert elements midway into the queue, or trying to remove elements out of order.

Stack

A Stack is a “Last In First Out” Collection, similar to a “stack” of dirty laundry on the floor. Elements can only added and removed from the top of the stack. In order to pick up the really dirty laundry at the very bottom of the pile, you must also pickup the things on top of it.

Deque

A Deque is a “double sided queue” that combines a Queue and a Stack. Elements can be added to start or the end of deque, and can be removed from the start or the end of the deque.

Leave a Reply

Your email address will not be published. Required fields are marked *