简体   繁体   中英

java Streams: collect taking in mind stream is empty

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!

As you need to use Stream s 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);
}

Old answer

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM