简体   繁体   English

java Streams:收集考虑流是空的

[英]java Streams: collect taking in mind stream is empty

I'd like to build a Sort object using this Optional -like code: 我想使用这个类似Optional的代码构建一个Sort对象:

private Sort buildSort(Collection<String> fields) {
    fields.stream()
        .map(this::buildOrder)
        .collect(Sort.unsorted(), ????, ????);
}

buildOrder is: buildOrder是:

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.unsorted() ,或者组合每个Sort对象。

Sort object has an and method that stands for building and concatenate orders. Sort对象有一个and方法,代表构建和连接订单。

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! 我需要使用stream-api!

As you need to use Stream s you can just use the this: 因为你需要使用Stream你可以使用这个:

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() . 由于buildOrder()方法不返回空的Sort.Order您最初可以检查fields是否为空,然后直接返回Sort.unsorted()

And for the combining of the sorts you may not even want to use a Stream but rather a normal loop: 对于各种类型的组合,您甚至可能不想使用Stream而是使用普通循环:

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 . 第二个map将每个Order转换为它自己的Sort The accumulator and combiner then just add Sorts together. 累加器和组合器然后只是添加Sorts

return fields.stream()
    .map(this::buildOrder)
    .map(Sort::by)
    .collect(Sort::unsorted, Sort::and, Sort::and);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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