Skip to content

A Java collection of value pairs? (tuples?)

In Java, you can use the AbstractMap.SimpleEntry class from the java.util package to represent a value pair (also known as a tuple). The SimpleEntry class is a mutable implementation of the Map.Entry interface, and it holds a pair of values (a key and a value). If you need an immutable pair, use AbstractMap.SimpleImmutableEntry instead.

Here is an example of how you can use the SimpleEntry class to create a collection of value pairs:


java
import java.util.AbstractMap;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

List<Map.Entry<String, Integer>> list = new ArrayList<>();
list.add(new AbstractMap.SimpleEntry<>("apple", 1));
list.add(new AbstractMap.SimpleEntry<>("banana", 2));
list.add(new AbstractMap.SimpleEntry<>("orange", 3));

for (Map.Entry<String, Integer> entry : list) {
    System.out.println(entry.getKey() + ": " + entry.getValue());
}

In this example, a List of Map.Entry objects is created, and the SimpleEntry class is used to create three value pairs (apple: 1, banana: 2, orange: 3). The getKey() and getValue() methods of the Map.Entry interface are used to access the key and value of each value pair.

Alternatively, you can use the Map.entry() static factory method to create value pairs. This method is defined directly on the Map interface and requires Java 9 or higher.

For example:


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

List<Map.Entry<String, Integer>> list = new ArrayList<>();
list.add(Map.entry("apple", 1));
list.add(Map.entry("banana", 2));
list.add(Map.entry("orange", 3));

for (Map.Entry<String, Integer> entry : list) {
    System.out.println(entry.getKey() + ": " + entry.getValue());
}

This code creates the same value pairs as the previous example, using the Map.entry() factory method.

I hope this helps! Let me know if you have any other questions.

Dual-run preview — compare with live Symfony routes.