Merge pull request #8739 from Isira-Seneviratne/Stream_average

Calculate search score using streams.
This commit is contained in:
Stypox 2022-10-30 22:09:55 +01:00 committed by GitHub
commit 8fdd828de4
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
1 changed files with 10 additions and 25 deletions

View File

@ -1,6 +1,7 @@
package org.schabi.newpipe.settings.preferencesearch; package org.schabi.newpipe.settings.preferencesearch;
import android.text.TextUtils; import android.text.TextUtils;
import android.util.Pair;
import org.apache.commons.text.similarity.FuzzyScore; import org.apache.commons.text.similarity.FuzzyScore;
@ -8,6 +9,7 @@ import java.util.Comparator;
import java.util.Locale; import java.util.Locale;
import java.util.Map; import java.util.Map;
import java.util.function.Function; import java.util.function.Function;
import java.util.stream.Collectors;
import java.util.stream.Stream; import java.util.stream.Stream;
public class PreferenceFuzzySearchFunction public class PreferenceFuzzySearchFunction
@ -72,39 +74,22 @@ public class PreferenceFuzzySearchFunction
); );
private final PreferenceSearchItem item; private final PreferenceSearchItem item;
private final float score; private final double score;
FuzzySearchSpecificDTO( FuzzySearchSpecificDTO(final PreferenceSearchItem item, final String keyword) {
final PreferenceSearchItem item,
final String keyword) {
this.item = item; this.item = item;
this.score = WEIGHT_MAP.entrySet().stream()
float attributeScoreSum = 0; .map(entry -> new Pair<>(entry.getKey().apply(item), entry.getValue()))
int countOfAttributesWithScore = 0; .filter(pair -> !pair.first.isEmpty())
for (final Map.Entry<Function<PreferenceSearchItem, String>, Float> we .collect(Collectors.averagingDouble(pair ->
: WEIGHT_MAP.entrySet()) { FUZZY_SCORE.fuzzyScore(pair.first, keyword) * pair.second));
final String valueToProcess = we.getKey().apply(item);
if (valueToProcess.isEmpty()) {
continue;
}
attributeScoreSum +=
FUZZY_SCORE.fuzzyScore(valueToProcess, keyword) * we.getValue();
countOfAttributesWithScore++;
}
if (countOfAttributesWithScore != 0) {
this.score = attributeScoreSum / countOfAttributesWithScore;
} else {
this.score = 0;
}
} }
public PreferenceSearchItem getItem() { public PreferenceSearchItem getItem() {
return item; return item;
} }
public float getScore() { public double getScore() {
return score; return score;
} }
} }