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 an immutable implementation of the Map.Entry
interface, and it holds a pair of values (a key and a value).
Here is an example of how you can use the SimpleEntry
class to create a collection of value pairs:
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.
Keep in mind that the SimpleEntry
class is an implementation of the Map.Entry
interface, so you can also use the Map.entry()
factory method to create value pairs.
For example:
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.