diff --git a/src/main/java/com/bakdata/util/seq2/Seq2.java b/src/main/java/com/bakdata/util/seq2/Seq2.java index 80b2b05..9979098 100644 --- a/src/main/java/com/bakdata/util/seq2/Seq2.java +++ b/src/main/java/com/bakdata/util/seq2/Seq2.java @@ -1,5 +1,5 @@ /* - * Copyright (c), 2024 bakdata GmbH + * Copyright (c), 2025 bakdata GmbH * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at @@ -1332,10 +1332,26 @@ default PairSeq zip(final Seq2 other) { return this.zip(other.toSeq()); } + /** + * Zips each element of this sequence with its zero-based index. + * + * @return a {@link PairSeq} whose elements are the original elements paired with their respective index (element, + * index) + * @see Seq#zipWithIndex() + */ default PairSeq zipWithIndex() { return PairSeq.seq(this.toSeq().zipWithIndex()); } + /** + * Similar to {@link #zipWithIndex()}, but index is used as {@link PairSeq} key. + * + * @return a {@link PairSeq} whose elements are the index paired with the original element (index, element) + */ + default PairSeq keyedByIndex() { + return this.zipWithIndex().swapped(); + } + /** * @see Seq#zipWithIndex() */ diff --git a/src/test/java/com/bakdata/util/seq2/Seq2Test.java b/src/test/java/com/bakdata/util/seq2/Seq2Test.java index ea10fce..407e4b7 100644 --- a/src/test/java/com/bakdata/util/seq2/Seq2Test.java +++ b/src/test/java/com/bakdata/util/seq2/Seq2Test.java @@ -92,4 +92,26 @@ void shouldFlatMapToIterablePair() { new Tuple2<>(2, 2), new Tuple2<>(3, 3)); } + @Test + void shouldZipWithIndex() { + assertThat((Stream>) Seq2.seq(List.of(10, 11, 12)) + .zipWithIndex() + ).containsExactlyInAnyOrder( + new Tuple2<>(10, 0L), + new Tuple2<>(11, 1L), + new Tuple2<>(12, 2L) + ); + } + + @Test + void shouldPairWithIndexKey() { + assertThat((Stream>) Seq2.seq(List.of(10, 11, 12)) + .keyedByIndex() + ).containsExactlyInAnyOrder( + new Tuple2<>(0L, 10), + new Tuple2<>(1L, 11), + new Tuple2<>(2L, 12) + ); + } + }