【问题标题】:Remove stop words from a hashmap从哈希图中删除停用词
【发布时间】:2013-08-15 02:10:16
【问题描述】:

我有一个哈希图,由作为单词(字符串)的键和作为计数(整数)的值组成。

我必须从哈希图中删除停用词。本质上,我必须为大约 67 个单词执行 hMap.remove("then") 、 hMpa.remove("where") 。有没有更简单的方法?我可以一次从哈希图中删除多个键吗?

【问题讨论】:

  • 不,将您的单词添加到列表中并在循环中为每个单词调用 remove。

标签: java hashmap key-value


【解决方案1】:

使用hMap.keySet().removeAll(the_stuff_you_want_to_remove)

来自documentation

set 支持元素移除,即通过 Iterator.remove、Set.remove、removeAll、retainAll 和 clear 操作从 map 中移除对应的映射。

【讨论】:

  • 是不是像 hMap.keySet().removeAll("then","where","apple" ) ?
  • @user2623946 你需要给它传递一个集合,你可以用你的67个词来弥补。
  • @user2623946 不,remove all 接收一个集合作为参数。
  • @user2623946 这是removeAll(Collection<?>)。因此,如果您有要在集合中删除的项目列表(如列表),只需传递它。
【解决方案2】:

@user2623946 不,您必须为此使用集合。 或者类似的东西:

String[] arr = {"a","b","c"};
myMap.keySet().removeAll(Arrays.asList(arr));

【讨论】:

    【解决方案3】:

    以下内容应该可以帮助您;

    Map<String, Integer> ohm = new HashMap<String, Integer>();
    List<String> al = new ArrayList<String>();
    al.add("One");
    al.add("Two");
    
    ohm.put("One", 1);
    ohm.put("Two", 2);
    ohm.put("Three", 3);
    
    ohm.keySet().removeAll(al);
    System.out.println(ohm);  // Output: [Three = 3]
    

    希望这会有所帮助。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2011-05-29
      • 2012-04-19
      • 1970-01-01
      • 2023-04-09
      • 2013-05-15
      • 2013-03-02
      相关资源
      最近更新 更多