简体   繁体   中英

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?

Triple is useful when you want to save 3 values at a time and you can pass different data types. If you just want to learn then below is an example of its usage but if you want to use in code then I would suggest you to use Objects instead.

public class Triple<T, U, V> {

    private final T first;
    private final U second;
    private final V third;

    public Triple(T first, U second, V third) {
        this.first = first;
        this.second = second;
        this.third = third;
    }

    public T getFirst() { return first; }
    public U getSecond() { return second; }
    public V getThird() { return third; }
}

And this is how you can instantiate it:

List<Triple<String, Integer, Integer>> = new ArrayList<>();

EDIT

As discussed in comments, please note that it belongs to org.apache.commons.lang3.tuple It is not a built-in class in Java.

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".

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM