【问题标题】:Search in HashMap based on data of the value根据值的数据在HashMap中搜索
【发布时间】:2018-12-22 19:07:26
【问题描述】:

我有一个包含 3 个属性的 Post 类:userIduserNamepostId。 每个帖子都会在数据库中生成一个唯一的 id(String),所以我将它保存在一个 HashMap 中,其中 Key 是唯一的帖子 id,值是 Post,如下所示:

HashMap<String, Post> posts = new HashMap<>(); posts.put(postId, new Post(userId, userName, postId)).

现在我想找到地图中的所有帖子,带有特定的userId。该怎么做?

【问题讨论】:

  • 没有什么特别的魔法。只需遍历值并选择匹配的值。
  • 相关:Java Hashmap: How to get key from value?类似的问题比较多,随便搜一下。
  • 季节的问候,欢迎来到 Stack Overflow。请告诉我们您的搜索和研究结果,以及它如何不足以解决您的问题。然后,我们知道要告诉您什么以帮助您朝着正确的方向前进。这适用于这个问题和所有其他 Stack Overflow 问题。

标签: java search hashmap


【解决方案1】:

您可以在 Map 的值中查找与提供的 userId 匹配的Posts:

public List<Post> search(HashMap<String, Post> posts, String userId){
  return
  posts.values()
       .stream()
       .filter(p -> p.getUserId().equals(userId))
       .collect(toList());
}

【讨论】:

    【解决方案2】:

    这应该可以解决问题,

    posts.values().stream().filter(p -> p.userId.equals("yourUserId")).collect(Collectors.toList());
    

    【讨论】:

      【解决方案3】:

      使用 HashMap 的当前结构,没有办法获取 userId 的帖子,而是通过迭代整个地图并比较每个值 userId

      如果你想在不循环HashMap的情况下高效地找到与特定UserId相关的所有帖子,那么你必须改变HashMap本身的结构,不要依赖数据库生成的postId作为hashMap 的键。相反,您应该使用 userId 作为 HashMap 的键:

      HashMap&lt;String, ArrayList&lt;Post&gt;&gt; posts = new HashMap&lt;&gt;();

      插入:

      public void addPost(String userId, Post newPost) {
          ArrayList<Post> postsForUserId = posts.get(userId);
          postsForUserId.add(newPost);
      }
      

      检索:

      public ArrayList<Post> getPosts(String userId) {
          return posts.get(userId);
      }
      

      【讨论】:

        【解决方案4】:

        这可以通过改变地图结构来完成。

        如果不需要具有与您相同的 Map 结构,则为您的特殊目的更改 Map 将解决您的问题。

        //Initialization of map where key is userId and value is list of Post objects.
        HashMap<String, List<Post>> postsByUserId = new HashMap<String, List<Post>>();
        
        //Insertion of post into map. 
        List<Post> postList = postsByUserId.get(post.userId);
        
        //Null check and initialization of List.
        if (postList == null) { 
            postList = new ArrayList<Post>();
            //Put list into map
            postsByUserId.put(post.userId, postList);
        }
        //Add object to the list. Either it will be the list retrieved from map or initialized above. 
        postList.add(post);
        
        //Retrieve list of post by userId
        List<Post> postListOfUserId = postsByUserId.get(userId);
        

        谢谢!

        【讨论】:

          猜你喜欢
          • 2018-10-04
          • 2017-02-03
          • 2017-05-07
          • 1970-01-01
          • 2020-05-03
          • 1970-01-01
          • 2012-04-01
          • 1970-01-01
          • 1970-01-01
          相关资源
          最近更新 更多