如何在Java8流中将两个String列表合并为一个列表而不重复

时间:2020-04-25 12:59:55

标签: java collections java-8 java-stream

在这里,我有两个项目列表,我想要合并到一个列表中并在保存到数据库之前删除重复项。但是我收到一个错误,即“无法从静态上下文中引用非静态方法”。尽管我知道该消息的含义,但是我不知道如何在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());

Here is the snapshot of the error message

3 个答案:

答案 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()可以解决此错误,并且应该已经成为一个问题了。