File tree Expand file tree Collapse file tree 2 files changed +39
-1
lines changed
main/java/com/bakdata/util/seq2
test/java/com/bakdata/util/seq2 Expand file tree Collapse file tree 2 files changed +39
-1
lines changed Original file line number Diff line number Diff line change 11/*
2- * Copyright (c), 2024 bakdata GmbH
2+ * Copyright (c), 2025 bakdata GmbH
33 * Licensed under the Apache License, Version 2.0 (the "License");
44 * you may not use this file except in compliance with the License.
55 * You may obtain a copy of the License at
@@ -1332,10 +1332,26 @@ default <U> PairSeq<T, U> zip(final Seq2<? extends U> other) {
13321332 return this .zip (other .toSeq ());
13331333 }
13341334
1335+ /**
1336+ * Zips each element of this sequence with its zero-based index.
1337+ *
1338+ * @return a {@link PairSeq} whose elements are the original elements paired with their respective index (element,
1339+ * index)
1340+ * @see Seq#zipWithIndex()
1341+ */
13351342 default PairSeq <T , Long > zipWithIndex () {
13361343 return PairSeq .seq (this .toSeq ().zipWithIndex ());
13371344 }
13381345
1346+ /**
1347+ * Similar to {@link #zipWithIndex()}, but index is used as {@link PairSeq} key.
1348+ *
1349+ * @return a {@link PairSeq} whose elements are the index paired with the original element (index, element)
1350+ */
1351+ default PairSeq <Long , T > keyedByIndex () {
1352+ return this .zipWithIndex ().swapped ();
1353+ }
1354+
13391355 /**
13401356 * @see Seq#zipWithIndex()
13411357 */
Original file line number Diff line number Diff line change @@ -92,4 +92,26 @@ void shouldFlatMapToIterablePair() {
9292 new Tuple2 <>(2 , 2 ), new Tuple2 <>(3 , 3 ));
9393 }
9494
95+ @ Test
96+ void shouldZipWithIndex () {
97+ assertThat ((Stream <Tuple2 <Integer , Long >>) Seq2 .seq (List .of (10 , 11 , 12 ))
98+ .zipWithIndex ()
99+ ).containsExactlyInAnyOrder (
100+ new Tuple2 <>(10 , 0L ),
101+ new Tuple2 <>(11 , 1L ),
102+ new Tuple2 <>(12 , 2L )
103+ );
104+ }
105+
106+ @ Test
107+ void shouldPairWithIndexKey () {
108+ assertThat ((Stream <Tuple2 <Long , Integer >>) Seq2 .seq (List .of (10 , 11 , 12 ))
109+ .keyedByIndex ()
110+ ).containsExactlyInAnyOrder (
111+ new Tuple2 <>(0L , 10 ),
112+ new Tuple2 <>(1L , 11 ),
113+ new Tuple2 <>(2L , 12 )
114+ );
115+ }
116+
95117}
You can’t perform that action at this time.
0 commit comments