I'd like to build a Sort object using this Optional-like code:
private Sort buildSort(Collection<String> fields) {
fields.stream()
.map(this::buildOrder)
.collect(Sort.unsorted(), ????, ????);
}
buildOrder is:
private Order buildOrder(String field) {
if (field.startsWith("-")) {
return Order.desc(field.substring(1));
}
else {
return Order.asc(field);
}
}
I need to return an Sort.unsorted() if stream is empty, or combine each Sort object.
Sort object has an and method that stands for building and concatenate orders.
Sort.by(sort1)
.and(sort2)...
So I need that:
if (stream is empty) then
return Sort.unsorted
else
return foreach item in stream:
Sort.by(item).and(item2).and(item3)...
Classes:
org.springframework.data.domain.Sort
org.springframework.data.domain.Sort.Order
NOTE
I need to use stream-api!
I believe this should work. The second map converts each Order to it's own Sort. The accumulator and combiner then just add Sorts together.
return fields.stream()
.map(this::buildOrder)
.map(Sort::by)
.collect(Sort::unsorted, Sort::and, Sort::and);
As you need to use Streams you can just use the this:
public Sort buildSort(Collection<String> fields) {
return fields.stream()
.map(this::buildOrder)
.map(Sort::by)
.reduce(Sort.unsorted(), Sort::and);
}
As the buildOrder() method doesn't return an empty Sort.Order you can just initially check if fields is empty and then directly return a Sort.unsorted().
And for the combining of the sorts you may not even want to use a Stream but rather a normal loop:
public Sort buildSort(Collection<String> fields) {
if(fields.isEmpty()) {
return Sort.unsorted();
}
Sort result = null;
for(String field : fields) {
Sort.Order order = buildOrder(field);
if(result == null) {
// initially create a Sort
result = Sort.by(order);
} else {
// then just concatenate them
result = result.and(order);
}
}
return result;
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With