Skip to content

About

Lightweight, zero-dependency, Stream-friendly Tuple library for Java 17+

Topics

Resources

Stars

3 stars

Watchers

0 watching

Forks

Latest commit

 

History

45 Commits

Folders and files

Repository files navigation

java-tuple

Maven Central Java CI Javadoc Java License

A lightweight, zero-dependency, Stream-friendly Tuple library for Java 17+.


Design Philosophy

java-tuple 2.0 is built around four deliberate design principles:

  1. Single entry point (Tuple): Import and reference only Tuple. Concrete types (Tuple1–Tuple8) are nested records inside public sealed interface Tuple and are meant to stay out of sight via var, lambda type inference, and Tuple::... method references.
  2. 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., via Tuple.mapping(MyRecord::new)).
  3. 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.
  4. Modern Java, zero dependencies: Built as a single public source file (Tuple.java) leveraging sealed interface, record, and Collectors::teeing, with no runtime dependencies.

Requirements

  • Java 17+ for 2.x (for Java 8+, use 1.x).

Maven

Add to pom.xml:

<dependencies>
    <dependency>
        <groupId>com.andrebreves</groupId>
        <artifactId>java-tuple</artifactId>
        <version>2.0.0</version>
    </dependency>
</dependencies>

Usage

Basics (var + Tuple)

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);

Stream Pipelines

Carry-along & enrichment (attaching, flatAttaching, appending, flatAppending)

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();

Projecting objects (projecting)

var namesAndAges = users.stream()
    .map(Tuple.projecting(User::name, User::age))                         // (name, age)
    .toList();

Method references (Tuple::v1..Tuple::v8, Tuple::reverse, Tuple::from)

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: Use Comparator.comparing(Tuple::v2, Comparator.reverseOrder()) instead of Comparator.comparing(Tuple::v2).reversed(). Chaining .reversed() breaks target-type propagation in Java, preventing the compiler from resolving the overloaded Tuple::v2 method reference.

Stream Utilities (zipWithIndex, pairwise, zip)

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());

Maps & Collectors

// 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());

API Overview

Static methods on Tuple

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)

Instance methods on Tuple1..Tuple8 (via var)

  • v1()..vN() — record component accessors
  • mapV1(fn)..mapVN(fn) — transform a single position, keeping all others unchanged
  • append(value) — return a Tuple(N+1) with the appended value (for degrees 1–7)
  • reverse() — return a tuple with values in reversed order
  • map(fn) — destructure values into a result or record
  • consume(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))

What Changed from 1.x

Version 2.0.0 is a focused redesign for modern Java and is not binary/source compatible with 1.x.

Architecture & Platform

  • Minimum Java version: Raised from Java 8 to Java 17 LTS (compatible with Java 17, 21, and 25).
  • Single-file sealed interface + nested records: Tuple1..Tuple8 are now public records nested inside public sealed interface Tuple (replacing top-level com.andrebreves.tuple.TupleN classes).
  • No code generator: Removed the com.andrebreves.tuple.generator package and build-time source generation.
  • JPMS support: Added Automatic-Module-Name: com.andrebreves.tuple.

Removed

  • Tuple0 and degrees 9–15: Max degree is now 8 (Tuple1–Tuple8). Beyond 8 unnamed values, prefer a record.
  • Comparable / compareTo: Removed because tuples often hold non-Comparable domain objects, making unconditional Comparable a runtime ClassCastException hazard. Use Comparator.comparing(Tuple::vN) instead.
  • degree(): Removed as tuples are not meant to be passed polymorphically as Tuple.
  • concat(TupleM): Removed to eliminate $O(N^2)$ method bloat; use append or Tuple.appending(...).
  • Public TupleN.of(...): Removed in favor of Tuple.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 like Comparator.comparing and Collectors.mapping), and instance mapValues / consumeValues / testValues → map / consume / test.

Added

  • 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::reverse and tuple.reverse() across all degrees 1..8.

About

Lightweight, zero-dependency, Stream-friendly Tuple library for Java 17+

Topics

Resources

Stars

3 stars

Watchers

0 watching

Forks

Releases

Used by

Contributors

Languages