3 回答
TA贡献1810条经验 获得超5个赞
听起来这个问题的症结在于您想要省略 中current没有匹配项的任何项目previous,但使用 中的实际对应值转换确实有匹配项previous的项目。在那种情况下flatMap就是你想要的。您可以使用flatMap将每个Order不转换为DiffOrders,而是转换为一个流,DiffOrders对于不匹配项,该流将是空的,并且由单个元素组成,用于匹配项。
List<DiffOrders> matchedOrders = current.stream()
.flatMap(curr -> {
Optional<Order> p = previous.stream()
.filter(prev -> OrderPredicate.orderSameDirectionAndSize(curr, prev))
.findFirst();
if (p.isPresent() && !p.get().qty.equals(curr.qty)) {
return Stream.of(new DiffOrders(curr.user, curr.tradeDate, curr.qty, p.get().qty));
} else {
return Stream.empty();
}
})
.collect(Collectors.toList());
TA贡献1802条经验 获得超5个赞
据我了解,这个问题的主要需求之一是 current 和 previous 的映射Order,这样您就可以MatchOrder从细节中构建出来。当然,这将需要在构建此类当前项到先前项的过程map中进行操作。filter
List<MatchOrders> matchedOrders = currentOrders.stream()
.map(curr -> new AbstractMap.SimpleEntry<>(curr, prevOrders.stream()
.filter(prev -> orderSameDirectionAndSize(curr, prev))
.findAny())) // <Order, Optional<Order>> currentToOptionalPrevious
.map(e -> {
Orders current = e.getKey();
Orders previous = e.getValue().orElse(current); // assumed a fallback
return new MatchOrders(current.getUser(), current.getQty(),
previous.getQty(), current.getDirection(), previous.getDirection());
})
.collect(Collectors.toList());
TA贡献1895条经验 获得超7个赞
对于简单的代码和简单的算法分两步就可以解决;
private List<DiffOrders> mergeLists(List<Orders> currentOrders, List<Orders> prevOrders) {
Map<String, List<Orders>> map = prevOrders.stream().collect(Collectors.groupingBy(order -> order.getUser() + order.getTradeDate()));
return currentOrders.stream().filter(current ->{
String key = current.getUser() + current.getTradeDate();
return map.get(key) != null && !map.get(key).isEmpty();
}).map(current -> mapper(current, map.get(current.getUser() + current.getTradeDate()))).collect(Collectors.toList());
}
private DiffOrders mapper(Orders current, List<Orders> list) {
DiffOrders diffOrders = new DiffOrders();
diffOrders.setCurrentQty(current.getQty());
diffOrders.setTradeDate(current.getTradeDate());
diffOrders.setUser(current.getUser());
diffOrders.setPrevQty(list.get(0).getQty());
return diffOrders;
}
添加回答
举报