如何在流中使用两个过滤器进行不同的转换

Fre*_*Goo 11 java java-8 java-stream

我只需要针对特定​​条件执行转换.我做这个转变:

// filter 1: less date - group by max date by groupId
        List<Info> listResult = new ArrayList<>(listInfo.stream()
                .filter(info -> info.getDate().getTime() < date.getTime())
                .collect(Collectors.groupingBy(Info::getGroupId, Collectors.collectingAndThen(
                        Collectors.reducing((Info i1, Info i2) -> i1.getDate().getTime() > i2.getDate().getTime() ? i1 : i2),
                        Optional::get))).values());
Run Code Online (Sandbox Code Playgroud)

但是对于超过指定日期的情况,我不需要转换任何东西,我只需要返回这些数据:

// filter 2: more date - nothing change in list
        List<Info> listMoreByDate = listInfo.stream()
                .filter(info -> info.getDate().getTime() >= date.getTime())
                .collect(Collectors.toList());
Run Code Online (Sandbox Code Playgroud)

接下来,要结合这两个过滤器 - 我将两个列表组合在一起:

listResult.addAll(listMoreByDate);
Run Code Online (Sandbox Code Playgroud)

我的问题是,这可以在一个流中完成吗?因为过滤器2绝对没用,它只返回这个条件的列表.

是否可以通过一个连续表达式执行这些转换?

我的完整代码:

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.stream.Collectors;

public class App {
    public static void main(String[] args) throws ParseException {
        Info info1 = new Info(1L, getDateFromStr("2018-02-02T10:00:00"), 3L);
        Info info2 = new Info(2L, getDateFromStr("2018-02-02T12:00:00"), 3L);
        Info info3 = new Info(3L, getDateFromStr("2018-02-05T12:00:00"), 6L);
        Info info4 = new Info(4L, getDateFromStr("2018-02-05T10:00:00"), 6L);

        Date date = getDateFromStr("2018-02-03T10:10:10");

        List<Info> listInfo = new ArrayList<>();
        listInfo.add(info1);
        listInfo.add(info2);
        listInfo.add(info3);
        listInfo.add(info4);

        // filter 1: less date - group by max date by groupId
        List<Info> listResult = new ArrayList<>(listInfo.stream()
                .filter(info -> info.getDate().getTime() < date.getTime())
                .collect(Collectors.groupingBy(Info::getGroupId, Collectors.collectingAndThen(
                        Collectors.reducing((Info i1, Info i2) -> i1.getDate().getTime() > i2.getDate().getTime() ? i1 : i2),
                        Optional::get))).values());

        // filter 2: more date - nothing change in list
        List<Info> listMoreByDate = listInfo.stream()
                .filter(info -> info.getDate().getTime() >= date.getTime())
                .collect(Collectors.toList());

        listResult.addAll(listMoreByDate);

        System.out.println("result: " + listResult);
    }

    private static Date getDateFromStr(String dateStr) throws ParseException {
        return new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss").parse(dateStr);
    }
}

class Info {
    private Long id;
    private Date date;
    private Long groupId;

    public Info(Long id, Date date, Long groupId) {
        this.id = id;
        this.date = date;
        this.groupId = groupId;
    }

    public Long getId() {
        return id;
    }

    public void setId(Long id) {
        this.id = id;
    }

    public Date getDate() {
        return date;
    }

    public void setDate(Date date) {
        this.date = date;
    }

    public Long getGroupId() {
        return groupId;
    }

    public void setGroupId(Long groupId) {
        this.groupId = groupId;
    }

    @Override
    public boolean equals(Object o) {
        if (this == o) return true;
        if (o == null || getClass() != o.getClass()) return false;
        Info info = (Info) o;
        return Objects.equals(id, info.id) &&
                Objects.equals(date, info.date) &&
                Objects.equals(groupId, info.groupId);
    }

    @Override
    public int hashCode() {

        return Objects.hash(id, date, groupId);
    }

    @Override
    public String toString() {
        final StringBuilder sb = new StringBuilder("Info{");
        sb.append("id=").append(id);
        sb.append(", date=").append(date);
        sb.append(", groupId=").append(groupId);
        sb.append('}');
        return sb.toString();
    }
}
Run Code Online (Sandbox Code Playgroud)

Hol*_*ger 10

我看不到任何简单的东西

List<Info> listResult = Stream.concat(
    listInfo.stream()
        .filter(info -> info.getDate().getTime() < date.getTime())
        .collect(Collectors.toMap(Info::getGroupId, Function.identity(),
            BinaryOperator.maxBy(Comparator.comparing(Info::getDate))))
        .values().stream(),
    listInfo.stream()
        .filter(info -> info.getDate().getTime() >= date.getTime())
    )
    .collect(Collectors.toList());
Run Code Online (Sandbox Code Playgroud)

因为这两个操作根本不同.Map在第一步中构建a 是不可避免的,因为它将用于识别具有相同getGroupId属性的项目.

也就是说,您应该考虑从使用切换Datejava.timeAPI.


Ous*_* D. 6

是的,您可以使用partitioningBy收集器合并这两个条件,如下所示:

 List<Info> resultSet = 
      listInfo.stream()
              .collect(collectingAndThen(partitioningBy(info -> info.getDate().getTime() < date.getTime()),
                     map -> Stream.concat(map.get(true)
                            .stream()
                            .collect(toMap(Info::getGroupId,
                                    Function.identity(),
                                    (Info i1, Info i2) -> i1.getDate().getTime() > i2.getDate().getTime() ? i1 : i2))
                            .values().stream(), map.get(false).stream())
                            .collect(Collectors.toCollection(ArrayList::new))));
Run Code Online (Sandbox Code Playgroud)

这基本上使用partitioningBy收集器来组织元素,使得所有元素都传递标准info.getDate().getTime() < date.getTime()以及它的错误,即哪里info -> info.getDate().getTime() >= date.getTime()是真的Map<Boolean, List<T>>.

此外,我们利用collectingAndThen集电极在所述施加精加工函数Map<Boolean, List<T>>由返回partitioningBy集热器,在这种情况下我们串接的应用逻辑的结果:

.collect(Collectors.groupingBy(Info::getGroupId, 
          Collectors.collectingAndThen(Collectors.reducing((Info i1, Info i2) -> i1.getDate().getTime() > i2.getDate().getTime() ? i1 : i2),
           Optional::get))))
.values();
Run Code Online (Sandbox Code Playgroud)

我简化为:

.collect(toMap(Info::getGroupId, Function.identity(), (Info i1, Info i2) -> i1.getDate().getTime() > i2.getDate().getTime() ? i1 : i2)))
.values();
Run Code Online (Sandbox Code Playgroud)

返回的元素返回info.getDate().getTime() < date.getTime()false(map.get(false).stream()).

最后,我们将结果收集到收集器的ArrayList实现中toCollection.