【问题标题】:How could I filter this ArrayList in Java [closed]我如何在 Java 中过滤这个 ArrayList [关闭]
【发布时间】:2021-03-24 13:10:29
【问题描述】:

我想知道如何过滤 Posts ArrayList 以获取 John 撰写的所有帖子

这是我的代码:

    Posts = new ArrayList<>();
    authors = new ArrayList<String>();
    authors.add("John");
    tags = new ArrayList<String>();
    tags.add("space");
    Posts.add(new Post(2, "First Post",authors, "Content", tags));

【问题讨论】:

  • 您需要指定更多信息,例如各个字段的编码方式、作者和帖子之间的关系等。否则此时的任何解决方案都是猜测。

标签: java list arraylist filter stream


【解决方案1】:

试试这个:

posts.stream()
        .filter(n -> n.getAuthors().contains("John"))
        .collect(Collectors.toList());

【讨论】:

    【解决方案2】:

    有一个方便的 removeIf 方法...

    posts.removeIf(p -> !p.getAuthors().contains("John"));
    

    -&gt; 代表一个函数。我们告诉removeIf 函数:要确定列表中的某个条目是否需要删除,请对其运行函数。该函数然后说:给定一个p(它是 Post 对象),对其调用 getAuthors,然后对其调用 .contains("John")。然后翻转布尔结果,瞧。如果为真,请将其删除。

    【讨论】:

      【解决方案3】:

      如果您需要通过其键(在本例中为 John)查找某些内容,您可以使用 hashmap。 它将为您提供该键的值。因此,您可以像这样在字符串的数组列表和不同的 autors 中创建不同的帖子:

          HashMap<String, ArrayList<String>> autors = new HashMap<String, ArrayList<String>>();
          ArrayList<String> posts= new ArrayList<String>();
          posts.add("Hello");
          posts.add("World.");
          hashmap.put("John", posts);
          System.out.println("Posts by John:"  + autors.get("John"));
      
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2013-05-06
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多