我想知道如何检查和检索 Map
内 List
的元素。
private Map<User, List<Offer>> shops = new ConcurrentHashMap<>(32);
//how to write this?
public List<Offer> getOffersOlderThan(int seconds){
return this.shops.values().stream().forEach(
x->x.stream()
.filter(y-> MyTime.currentTime.minusSeconds(seconds)
.isBefore(y.getOfferBegin()))
}
我已经尝试使用 filter
代替第一个 forEach
,但这也不起作用。
我想检索在 currentTime - 秒
之前具有 Timestamp
的所有 Offer
的 List
.
如何使用 Java 8 返回通用列表? 例如:
public List<Offer> getOffersByUser(User u){
return this.shops.entrySet().stream().filter(x->x.getKey().getId()==u.getId())
.collect(List::new) //how to parameterize?
}
最佳答案
对于所有优惠,请使用 flatMap()
和 collect()
return shops.values().stream()
.flapMap(List::stream)
.filter(y-> MyTime.currentTime.minusSeconds(seconds).isBefore(y.getOfferBegin())
.collect(Collectors.toList());
仅针对用户的优惠:
return shops.getOrDefault(user, Collections.emptyList())
.filter(y-> MyTime.currentTime.minusSeconds(seconds).isBefore(y.getOfferBegin())
.collect(Collectors.toList());
关于Java 8 版本 - 带条件的列表映射,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40954247/