【问题标题】:Is there a way to filter out the elements of a List containing object having a String element based on another List of String有没有办法根据另一个字符串列表过滤出包含具有字符串元素的对象的列表的元素
【发布时间】:2016-11-22 11:03:22
【问题描述】:

我有一个对象列表List<Object>,其中对象包含字符串元素。现在还有另一个字符串列表List<String>

我希望第一个列表只包含属于第二个列表元素的对象。

最有效的方法是什么?

【问题讨论】:

  • 您应该使用Set 而不是List 来查找您想要查找的任何内容。
  • @Jean-FrançoisCorbett 我通过迭代列表来做到这一点,我认为这是最简单的解决方案。

标签: java string list


【解决方案1】:

您可以使用列表的contains() 方法,这在您的情况下很方便,因为它将equals() 检查字符串。

例如

  List<String> otherList = new ArrayList<>();
  List<Object> test = new ArrayList<>();
  Iterator<Object> it = test.iterator();
  while(it.hasNext()){
       if(!otherList.contains(it.next().getString())) it.remove();
   }

或在 Java8 流中

 test.stream().filter(e -> otherList.contains(e.getString()))
                .collect(Collectors.toList());

这将为您生成一个新的List

【讨论】:

    猜你喜欢
    • 2012-10-11
    • 1970-01-01
    • 2019-08-03
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-11-14
    • 2023-01-18
    • 2020-06-02
    相关资源
    最近更新 更多