Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
18 changes: 17 additions & 1 deletion src/main/java/com/bakdata/util/seq2/Seq2.java
Original file line number Diff line number Diff line change
@@ -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
Expand Down Expand Up @@ -1332,10 +1332,26 @@ default <U> PairSeq<T, U> zip(final Seq2<? extends U> 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<T, Long> 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<Long, T> keyedByIndex() {
return this.zipWithIndex().swapped();
}

/**
* @see Seq#zipWithIndex()
*/
Expand Down
22 changes: 22 additions & 0 deletions src/test/java/com/bakdata/util/seq2/Seq2Test.java
Original file line number Diff line number Diff line change
Expand Up @@ -92,4 +92,26 @@ void shouldFlatMapToIterablePair() {
new Tuple2<>(2, 2), new Tuple2<>(3, 3));
}

@Test
void shouldZipWithIndex() {
assertThat((Stream<Tuple2<Integer, Long>>) 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<Tuple2<Long, Integer>>) Seq2.seq(List.of(10, 11, 12))
.keyedByIndex()
).containsExactlyInAnyOrder(
new Tuple2<>(0L, 10),
new Tuple2<>(1L, 11),
new Tuple2<>(2L, 12)
);
}

}
Loading