A lightweight, zero-dependency, Stream-friendly Tuple library for Java 17+.
java-tuple 2.0 is built around four deliberate design principles:
- Single entry point (
Tuple): Import and reference onlyTuple. Concrete types (Tuple1–Tuple8) are nestedrecords insidepublic sealed interface Tupleand are meant to stay out of sight viavar, lambda type inference, andTuple::...method references. - Ephemeral, local data only: Tuples are intended strictly for transient intermediate transformations inside methods and Stream pipelines. For anything long-lived, domain-meaningful, or crossing method boundaries, materialize into a Java
record(e.g., viaTuple.mapping(MyRecord::new)). - Symmetry across degrees 1–8: Every polymorphic operation supports degrees 1 through 8 uniformly, so adding or removing a field mid-pipeline does not force rewrites downstream.
- Modern Java, zero dependencies: Built as a single public source file (
Tuple.java) leveragingsealed interface,record, andCollectors::teeing, with no runtime dependencies.
- Java 17+ for
2.x(for Java 8+, use1.x).
Add to pom.xml:
<dependencies>
<dependency>
<groupId>com.andrebreves</groupId>
<artifactId>java-tuple</artifactId>
<version>2.0.0</version>
</dependency>
</dependencies>import com.andrebreves.tuple.Tuple;
var pair = Tuple.of("v1", 2);
System.out.println(pair.v1()); // "v1"
System.out.println(pair.v2()); // 2
var updated = pair.mapV2(n -> n * 10); // ["v1", 20]
var triple = updated.append(true); // ["v1", 20, true]
var flipped = pair.reverse(); // [2, "v1"]
// Materialize into a record when leaving the local scope
record Item(String name, int qty, boolean active) {}
Item item = triple.map(Item::new);record UserRanking(String name, int score, int rank) {}
List<UserRanking> topUsers = users.stream()
.map(Tuple.attaching(this::fetchScore)) // (user, score)
.map(Tuple.appending((user, score) -> computeRank(user, score))) // (user, score, rank)
.filter(Tuple.testing(Tuple::v3, rank -> rank <= 10)) // filter by a single position
.sorted(Comparator.comparing(Tuple::v2, Comparator.reverseOrder()))
.map(t -> t.mapV1(User::name)) // transform a single position
.map(Tuple.mapping(UserRanking::new)) // tuple -> record
.toList();Expand nested collections while keeping the parent element:
var orderItems = orders.stream()
.flatMap(Tuple.flatAttaching(order -> order.items().stream())) // (order, item)
.filter(Tuple.testing((order, item) -> item.quantity() > 0))
.toList();var namesAndAges = users.stream()
.map(Tuple.projecting(User::name, User::age)) // (name, age)
.toList();var tuples = List.of(
Tuple.of("a", 1, "x"),
Tuple.of("b", 2, "y"),
Tuple.of("c", 3, "z")
);
tuples.stream()
.map(Tuple::v3)
.forEachOrdered(System.out::print); // "xyz"
tuples.stream()
.map(Tuple::reverse) // ("x", 1, "a"), ...
.forEach(Tuple.consuming((v1, v2, v3) -> System.out.println(v1 + ":" + v2)));Tip on sorting with
Comparator.comparing: UseComparator.comparing(Tuple::v2, Comparator.reverseOrder())instead ofComparator.comparing(Tuple::v2).reversed(). Chaining.reversed()breaks target-type propagation in Java, preventing the compiler from resolving the overloadedTuple::v2method reference.
All stream utilities are lazy and propagate Stream.close() to their input stream(s):
// Attach 0-based index
var indexed = Tuple.zipWithIndex(names.stream().filter(s -> !s.isBlank()))
.toList(); // (0L, name0), (1L, name1), ...
// Consecutive sliding pairs (a, b), (b, c), ...
var deltas = Tuple.pairwise(prices.stream())
.map(Tuple.mapping((prev, curr) -> curr - prev))
.toList();
// Zip 2 or 3 streams lazily
var paired = Tuple.zip(names.stream(), scores.stream())
.collect(Tuple.toMap());// Stream a Map directly as (key, value) tuples
var inverted = Tuple.stream(map)
.map(Tuple::reverse)
.collect(Tuple.toMap((a, b) -> a));
// Or convert Map.Entry via method reference
var entries = map.entrySet().stream()
.map(Tuple::from)
.filter(Tuple.testing((k, v) -> v > 0))
.collect(Tuple.toMap());
// Multiple aggregations in a single pass
var stats = numbers.stream()
.collect(Tuple.collecting(
Collectors.counting(),
Collectors.averagingInt(Integer::intValue)
));
System.out.println(stats.v1() + " items, avg " + stats.v2());| Category | Methods |
|---|---|
| Creation & Projection | of(v1..v8), from(Map.Entry), attaching(fn), flatAttaching(fn), projecting(f1..f8) |
| Access & Structure | v1(tuple)..v8(tuple), reverse(tuple) |
| Stream Operators | mapping(fn), consuming(consumer), testing(predicate), testing(extractor, predicate), appending(fn), flatAppending(fn) |
| Stream Utilities | zipWithIndex(stream), pairwise(stream), zip(s1, s2), zip(s1, s2, s3) |
| Maps & Collectors | stream(Map), toMap(...), collecting(c1..c8) |
v1()..vN()— record component accessorsmapV1(fn)..mapVN(fn)— transform a single position, keeping all others unchangedappend(value)— return aTuple(N+1)with the appended value (for degrees 1–7)reverse()— return a tuple with values in reversed ordermap(fn)— destructure values into a result orrecordconsume(consumer)— destructure values into a consumer (e.g.tuple.consume(repository::save))test(predicate)— destructure values into a predicate (e.g.tuple.test(validator::isEligible))
Version 2.0.0 is a focused redesign for modern Java and is not binary/source compatible with 1.x.
- Minimum Java version: Raised from Java 8 to Java 17 LTS (compatible with Java 17, 21, and 25).
- Single-file
sealed interface+ nestedrecords:Tuple1..Tuple8are nowpublic records nested insidepublic sealed interface Tuple(replacing top-levelcom.andrebreves.tuple.TupleNclasses). - No code generator: Removed the
com.andrebreves.tuple.generatorpackage and build-time source generation. - JPMS support: Added
Automatic-Module-Name: com.andrebreves.tuple.
-
Tuple0and degrees 9–15: Max degree is now 8 (Tuple1–Tuple8). Beyond 8 unnamed values, prefer arecord. -
Comparable/compareTo: Removed because tuples often hold non-Comparabledomain objects, making unconditionalComparablea runtimeClassCastExceptionhazard. UseComparator.comparing(Tuple::vN)instead. -
degree(): Removed as tuples are not meant to be passed polymorphically asTuple. -
concat(TupleM): Removed to eliminate$O(N^2)$ method bloat; useappendorTuple.appending(...). -
Public
TupleN.of(...): Removed in favor ofTuple.of(...)as the single factory entry point. -
Renamed stream adapters and instance destructuring:
Tuple.mapValues→Tuple.mapping,Tuple.consumeValues→Tuple.consuming,Tuple.testValues→Tuple.testing(aligned with JDK conventions likeComparator.comparingandCollectors.mapping), and instancemapValues/consumeValues/testValues→map/consume/test.
- Stream pipeline helpers:
Tuple.attaching,Tuple.flatAttaching,Tuple.projecting,Tuple.appending,Tuple.flatAppending,Tuple.testing. - Stream utilities:
Tuple.zipWithIndex(stream),Tuple.pairwise(stream),Tuple.zip(...). - Map & Collector helpers:
Tuple.from(Map.Entry),Tuple.stream(Map),Tuple.toMap(...),Tuple.collecting(...). - Reversal:
Tuple::reverseandtuple.reverse()across all degrees1..8.