Refactor creation of a list with java 8 streams

Viewed 220

I found the following code, which adds an item under certain circumstances (if its not OLD) to a list. This list get's packed in a common controls list afterwards.

    List<ListDataContent> list = new ArrayList<>();

    for (KonditionValue kondition : konditions) {
        if (kondition.getStatusKz().equals(StatusKz.OLD))
            continue;
        for (TermKondValue tilg : kondition.getTermimKonditions()) {
            if (tilg.getStatusKz().equals(StatusKz.OLD))
                continue;

            TerminKondListContent listContent = new TerminKondListContent(tilg, kondition.getChangeDatum(), funds);
            list.add(listContent);
        }
    }

    SimpleListControl listCtrl = new SimpleListControl();
    listCtrl.setDataModel(new ListDataModel(list));

I tried the following refactoring using java8 streams:

List<ListDataContent> list = konditionen.stream().map(kondition -> map(tilg, kondition.getChangeDate(), funds)).sorted().collect(Collectors.toList());
SimpleListControl listCtrl = new SimpleListControl();
listCtrl.setDataModel(new ListDataModel(list));

The problem is the map method...

private TerminKondListContent map(TermKondValue tilg, Date changeDate, BigDecimal funds) {
    if (kondition.getStatusKz().equals(StatusKz.OLD))
        return null;
    for (TermKondValue zins : kondition.getTerminkonditions()) {
        if (zins.getStatusKz().equals(StatusKz.OLD))
            return null;

        return new TerminKondListContent(tilg, changeDate, funds);
    }
    return null;
}

What can I do in the continue cases? return null? I could then filter null Values from the stream via

list.stream().filter( Objects::nonNull )

Is the use of Optionals an option here?

1 Answers
Related