scala java

Just a quick post about Tuples in Scala and how to build your own Tuple2 class on Java

A Tuple2 is a class that holds a tuple of 2 elements, e.g., (1, "Hello")

Here is the Java class

package es.rubenjgarcia.tuple;

public class Tuple2<T1, T2> {

    public final T1 _1;
    public final T2 _2;

    public Tuple2(T1 _1, T2 _2) {
        this._1 = _1;
        this._2 = _2;
    }

    public static <T1, T2> Tuple2<T1, T2> Tuple2(T1 _1, T2 _2) {
        return new Tuple2<>(_1, _2);
    }

    @Override
    public String toString() {
        return "(" + _1.toString() + ", " + _2.toString() + ")";
    }
}

And heres an example to show you how to use it

package es.rubenjgarcia.tuple;

import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;
import java.util.stream.IntStream;

import static es.rubenjgarcia.tuple.Tuple2.Tuple2;

public class Examples {

    public static void main(String[] args) {
        Tuple2<Integer, String> tuple = Tuple2(1, "Hello");
        System.out.println(tuple._1);
        System.out.println(tuple._2);
        System.out.println(tuple);

        List<String> words = Arrays.asList("Hello", "world");
        List<Tuple2> tuples = IntStream.range(0, words.size())
                .mapToObj(i -> Tuple2(i, words.get(i)))
                .collect(Collectors.toList());
        System.out.println(tuples);
    }
}

This is the output from this example

1
Hello
(1, Hello)
[(0, Hello), (1, world)]