Skip to content

Commit f3c95a5

Browse files
maennchensschuberth
authored andcommitted
fix(utils): detect key‑based duplicates in Set inputs
`Iterable<T>.getDuplicates(keySelector)` returned no results when the receiver was a `Set`, even if different elements shared the same key. The early‑exit shortcut has been removed, so logical duplicates are now reported correctly. Changes * Drop Set fast‑path in `getDuplicates(keySelector)`; keep it only for the zero‑arg variant where it is safe. * Align zero‑arg implementation and add regression tests. Signed-off-by: Jonatan Männchen <[email protected]>
1 parent 927e47c commit f3c95a5

File tree

2 files changed

+12
-2
lines changed

2 files changed

+12
-2
lines changed

utils/common/src/main/kotlin/IterableUtils.kt

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -46,12 +46,12 @@ fun Iterable<Int>.collapseToRanges(): List<Pair<Int, Int>> {
4646
* Return a map that associates duplicates as identified by [keySelector] with belonging lists of entries.
4747
*/
4848
fun <T, K> Iterable<T>.getDuplicates(keySelector: (T) -> K): Map<K, List<T>> =
49-
if (this is Set) emptyMap() else groupBy(keySelector).filter { it.value.size > 1 }
49+
groupBy(keySelector).filter { it.value.size > 1 }
5050

5151
/**
5252
* Return a set of duplicate entries in this [Iterable].
5353
*/
54-
fun <T> Iterable<T>.getDuplicates(): Set<T> = getDuplicates { it }.keys
54+
fun <T> Iterable<T>.getDuplicates(): Set<T> = if (this is Set) emptySet() else getDuplicates { it }.keys
5555

5656
/**
5757
* Return the next value in the iteration, or null if there is no next value.

utils/common/src/test/kotlin/IterableUtilsTest.kt

Lines changed: 10 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -95,6 +95,16 @@ class IterableUtilsTest : WordSpec({
9595
"b" to listOf("a" to "b", "b" to "b"),
9696
"z" to listOf("a" to "z", "o" to "z")
9797
)
98+
99+
val strings = setOf(
100+
"aaa",
101+
"bbb",
102+
"cc"
103+
)
104+
105+
strings.getDuplicates { it.length } shouldBe mapOf(
106+
3 to listOf("aaa", "bbb")
107+
)
98108
}
99109
}
100110
})

0 commit comments

Comments
 (0)