在这里,我有两个项目列表,我想要合并到一个列表中并在保存到数据库之前删除重复项。但是我收到一个错误,即“无法从静态上下文中引用非静态方法”。尽管我知道该消息的含义,但是我不知道如何在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());
答案 0 :(得分:0)
使用distinct()
Stream.of(currentItems.get(),itemsToAdd)
.flatMap(List::stream)
.distinct()
.collect(Collectors.toList());
答案 1 :(得分:0)
currentItems
不是List
而是Optional
,因此后续方法没有意义。解开Optional
,因此可以省略currentItems.isPresent()
。方法Stream::distinct
确保唯一项(或使用Set
):
final Shop shop = shopSrevice.getShopById(shopId);
final Optional<List<String>> currentItems= shop.getCurrentItems();
final List<String> currentItemsList = currentItems.orElse(Collections.emptyList());
List<String> allItems = Stream.of(currentItemsList, itemsToAdd)
.flatMap(Collection::stream)
.distinct()
.collect(Collectors.toList());
答案 2 :(得分:0)
问题是,您正在尝试制作可选列表和列表的流。在currentItems上调用get()
可以解决此错误,并且应该已经成为一个问题了。