在使用流
重构下面的代码片段到java8的过程中private Date getDate(List<BrowseHistory> historyList, String subscribe, String cancelled) {
for(int i=0; i<= historyList.size(); i++) {
if(isContainsStatus(historyList.get(i), subscribe) && isExist(historyList, cancelled, i)) {
return historyList.get(i).getCreated()
}
}
return null;
}
private boolean isExist(List<BrowseHistory> historyList, String status, int i) {
return historyList.size() == i+1 || (isContainsStatus(historyList.get(i+1), status) || isContainsStatus(historyList.get(i+1), Status.PEND.toString()));
}
private boolean isContainsStatus(BrowseHistory history, String status) {
return history.getStatus().contains(status);
}
我能够使用java8过滤器重构到if块,
以下是Java8重构代码
private Date getDate(List<BrowseHistory> historyList, String subscribe, String cancelled) {
return IntStream.range(0, historyList.size())
.filter(i -> isContainsStatus(historyList.get(i), subscribe) && isStatusExist(historyList, cancelled, i))
.mapToObj(historyList::get)
.map(BrowseHistory::getCreated)
.findFirst() // find first that got through those filters
.orElse(null);
}
根据以下答案编辑java8重构代码。
答案 0 :(得分:4)
java 8中应该有与java-8之前相同的方法。
i <= historyList.size()
但很少注意到:
i < historyList.size()
我宁愿使用{{1}}