diff --git a/modules/search-pipeline-common/src/main/java/org/opensearch/search/pipeline/common/SortResponseProcessor.java b/modules/search-pipeline-common/src/main/java/org/opensearch/search/pipeline/common/SortResponseProcessor.java index 2faa1f7efb92e..b6a621b738071 100644 --- a/modules/search-pipeline-common/src/main/java/org/opensearch/search/pipeline/common/SortResponseProcessor.java +++ b/modules/search-pipeline-common/src/main/java/org/opensearch/search/pipeline/common/SortResponseProcessor.java @@ -23,11 +23,10 @@ import org.opensearch.search.pipeline.SearchResponseProcessor; import java.util.ArrayList; -import java.util.Comparator; +import java.util.Collections; import java.util.List; import java.util.Map; import java.util.Objects; -import java.util.stream.Collectors; /** * Processor that sorts an array of items. @@ -166,14 +165,26 @@ public SearchResponse processResponse(SearchRequest request, SearchResponse resp return response; } - private > List getSortedValues(List values) { - List comparableValues = new ArrayList<>(values.size()); + private List getSortedValues(List values) { + // Downcast list elements to comparable (or throw exception) so we can sort + List> comparableValues = getComparableValues(values); + if (sortOrder.equals(SortOrder.ASCENDING)) { + Collections.sort(comparableValues); + } else { + Collections.sort(comparableValues, Collections.reverseOrder()); + } + // Upcast list elements back to Object + return new ArrayList<>(comparableValues); + } + + private List> getComparableValues(List values) { + List> comparableValues = new ArrayList<>(values.size()); for (Object obj : values) { if (obj == null) { throw new IllegalArgumentException("field [" + sortField + "] contains a null value.]"); } else if (Comparable.class.isAssignableFrom(obj.getClass())) { @SuppressWarnings("unchecked") - T comp = (T) obj; + Comparable comp = (Comparable) obj; comparableValues.add(comp); } else { throw new IllegalArgumentException( @@ -181,9 +192,7 @@ private > List getSortedValues(List valu ); } } - return comparableValues.stream() - .sorted(sortOrder.equals(SortOrder.ASCENDING) ? Comparator.naturalOrder() : Comparator.reverseOrder()) - .collect(Collectors.toList()); + return comparableValues; } static class Factory implements Processor.Factory {