【问题标题】:How to compare lists with duplicate values and return list with common items [closed]如何比较具有重复值的列表并返回具有常见项目的列表[关闭]
【发布时间】:2021-04-05 19:14:48
【问题描述】:

如何将 compare(List, List) 实现为一个返回公共值列表而不统一重复值的函数。

例子:

compare(List.of("1","2", "3", "1"), List.of("1", "1", "3", "4")) // [1, 1, 3]
compare(List.of("1","2", "3"), List.of("1", "3", "1")) // [1, 3]
compare(List.of("1","2", "1"), List.of("3")) // []

【问题讨论】:

标签: java lambda


【解决方案1】:

如果你不关心结果的顺序,那么:

    private List<String> compare(List<String> l1, List<String> l2) {
        var ll = new ArrayList<>(l2);
        return l1.stream()
                .filter(ll::remove)
                .collect(Collectors.toList());

    }

【讨论】:

  • ArrayList 是一个解决方案,因为 HashSet 删除了 ll 集中的重复项。感谢您的回复。
  • @AkifHadziabdic 改回来了。
猜你喜欢
  • 2018-02-10
  • 1970-01-01
  • 2020-11-03
  • 1970-01-01
  • 2021-01-06
  • 1970-01-01
  • 1970-01-01
  • 2018-11-30
  • 2019-03-07
相关资源
最近更新 更多