From 373b7ce682b2d182a75a0af262996b1299ee459b Mon Sep 17 00:00:00 2001 From: DBotThePony Date: Wed, 29 May 2024 12:33:40 +0700 Subject: [PATCH] reduce() without identity --- gradle.properties | 2 +- .../ru/dbotthepony/kommons/collect/StreamyIterators.kt | 10 ++++++++++ 2 files changed, 11 insertions(+), 1 deletion(-) diff --git a/gradle.properties b/gradle.properties index e427997..22c9bfc 100644 --- a/gradle.properties +++ b/gradle.properties @@ -4,7 +4,7 @@ kotlin.code.style=official specifyKotlinAsDependency=false projectGroup=ru.dbotthepony.kommons -projectVersion=2.18.0 +projectVersion=2.18.1 guavaDepVersion=33.0.0 gsonDepVersion=2.8.9 diff --git a/src/main/kotlin/ru/dbotthepony/kommons/collect/StreamyIterators.kt b/src/main/kotlin/ru/dbotthepony/kommons/collect/StreamyIterators.kt index 52ce11f..2b23d14 100644 --- a/src/main/kotlin/ru/dbotthepony/kommons/collect/StreamyIterators.kt +++ b/src/main/kotlin/ru/dbotthepony/kommons/collect/StreamyIterators.kt @@ -1,5 +1,6 @@ package ru.dbotthepony.kommons.collect +import ru.dbotthepony.kommons.util.KOptional import java.util.* import java.util.function.Predicate import java.util.stream.Collector @@ -218,6 +219,15 @@ inline fun Iterator.reduce(identity: T, reducer: (T, T) -> T): T { return result } +inline fun Iterator.reduce(reducer: (T, T) -> T): KOptional { + if (!hasNext()) + return KOptional() + + var result = next() + while (hasNext()) result = reducer.invoke(result, next()) + return KOptional(result) +} + fun Iterator.filterNotNull(): MutableIterator = filter { it != null } as MutableIterator inline fun Iterator<*>.filterIsInstance(): MutableIterator = filter { it is T } as MutableIterator