【发布时间】:2020-04-25 12:59:55
【问题描述】:
在这里,我有两个项目列表,我想将它们合并到一个列表中,并在保存到数据库之前删除重复项。但我收到“无法从静态上下文引用非静态方法”的错误。虽然我知道该消息的含义,但我不知道如何在 Java8 Stream 的上下文中解决它。请帮忙。
public void addItems(String shopId, List<String>itemsToAdd, String adminId) {
final Shop shop = shopSrevice.getShopById(shopId);
final Optional<List<String>> currentItems= shop.getCurrentItems();
if (currentItems.isPresent()){
List<String> allItems = Stream.of(currentItems,itemsToAdd)
.flatMap(Collection::stream)
.collect(Collectors.toList());
【问题讨论】:
-
错字?你只是没有像
List<String> allItems = Stream.of(currentItems.get(),itemsToAdd) .flatMap(Collection::stream) .collect(Collectors.toList());那样在isPresent之后调用get,并且可能没有检查你可以简单地执行List<String> allItems = Stream.of(currentItems.orElse(Collections.emptyList()), itemsToAdd) .flatMap(Collection::stream) .collect(Collectors.toList());
标签: java collections java-8 java-stream