java Streams: collect taking in mind stream is empty

Jordi :

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!

Michael :

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);

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=111277&siteId=1