【问题标题】:How do I merge two List of String into one List without duplicate in Java8 streamjava - 如何在Java 8流中将两个字符串列表合并到一个列表中而不重复
【发布时间】: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());

Here is the snapshot of the error message

【问题讨论】:

  • 错字?你只是没有像List&lt;String&gt; allItems = Stream.of(currentItems.get(),itemsToAdd) .flatMap(Collection::stream) .collect(Collectors.toList());那样在isPresent之后调用get,并且可能没有检查你可以简单地执行List&lt;String&gt; allItems = Stream.of(currentItems.orElse(Collections.emptyList()), itemsToAdd) .flatMap(Collection::stream) .collect(Collectors.toList());

标签: java collections java-8 java-stream


【解决方案1】:

问题是您正在尝试制作可选列表和列表的流。在 currentItems 上调用 get() 可以解决此错误,并且应该不是问题,因为您已经在检查它是否存在。

【讨论】:

  • 是的,兄弟,在 currentItems 上调用 get() 实际上解决了错误。谢谢。
  • 它没有,它只有在 Optional 不为空时才有效,这不能保证。如果 Optional 为空,则会引发异常。这就是为什么我建议使用 Optional.orElse 方法,该方法提供一个空集合以在 Optional 为空时返回。
【解决方案2】:

使用distinct()

Stream.of(currentItems.get(),itemsToAdd)
        .flatMap(List::stream)
        .distinct()
        .collect(Collectors.toList());

【讨论】:

    【解决方案3】:

    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());
    

    【讨论】:

    • 好的,谢谢大家的回答,调用currentItems上的get()确实解决了错误。
    猜你喜欢
    • 2018-04-03
    • 2013-10-10
    • 1970-01-01
    • 1970-01-01
    • 2018-03-08
    • 1970-01-01
    • 2017-07-08
    • 2018-06-05
    • 1970-01-01
    相关资源
    最近更新 更多