Refactoring list creation using java 8 threads

I found the following code that adds an item under certain circumstances (if it's not OLD) to the list. After that, the list will be packed into a general management list.

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 threads:

 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 if I continue? return null? Then I could filter the null values ​​from the stream through

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

Is Optionals used here?

+5
source share
1 answer

It is not, but you can have the following

 List<ListDataContent> list = konditions.stream() .filter(kondition -> !kondition.getStatusKz().equals(StatusKz.OLD)) .flatMap(kondition -> kondition.getTerminTilgkonditions() .stream() .filter(tilg -> !tilg.getStatusKz().equals(StatusKz.OLD)) .map(tilg -> new AbstractMap.SimpleEntry<>(kondition, tilg)) ) .map(e -> new TerminKondTilgListContent(e.getValue(), e.getKey().getChangeDatum(), funds)) .collect(Collectors.toList()); 

This creates a Stream<KonditionValue> and saves only those where the status is not StatusKz.OLD . Then it densely displays each of them in their TermKondTilgValue , where only TermKondTilgValue , which has the status not StatusKz.OLD .

Please note that we keep the reference to both TermKondTilgValue and KonditionValue , because we will need them later, so we use AbstractMap.SimpleEntry as a holder for two values.

Finally, this stream is mapped to the corresponding TerminKondTilgListContent and collected into a list.

+2
source

Source: https://habr.com/ru/post/1245709/


All Articles