'What is a Triple in Java?

I've come across code that looks like the following:

public List<Triple<String, String, Instant>> methodName() {
    // Do something
}

What is the Triple, how should It be used?



Solution 1:[1]

Think "tuple" for 3 values!

Many programming languages provide means to efficiently deal with lists of a "fixed" length but different types for each entry.

That Triple class is the Java way of providing you something like that. Like a Pair, but one more entry.

At its core, a fixed length tuple allows you to "loosely couple" multiple values of different types based on some sort of "ordering".

Solution 2:[2]

When you need a data structure to deal with a list of three entities, you might use a Triple. Here's a small example:

import java.util.ArrayList;
import java.util.List;
import org.apache.commons.lang3.tuple.Triple;
    
public class Test {

    public static void main(String[] args) {
        List<Triple<Integer, String, String>> tripleList = new ArrayList<>();
        tripleList.add(Triple.of(100, "Japan", "Tokyo"));
        tripleList.add(Triple.of(200, "Italy", "Rome"));
        tripleList.add(Triple.of(300, "France", "Paris"));

        for (Triple<Integer, String, String> triple : tripleList) {
            System.out.println("Triple left = " + triple.getLeft());
            System.out.println("Triple right = " + triple.getRight());
            System.out.println("Triple middle = " + triple.getMiddle());
        }
    }

}

Output:

Triple left = 100
Triple right = Tokyo
Triple middle = Japan
Triple left = 200
Triple right = Rome
Triple middle = Italy
Triple left = 300
Triple right = Paris
Triple middle = France

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1
Solution 2 Community