【问题标题】:How to remove from a set如何从集合中删除
【发布时间】:2013-10-12 04:35:56
【问题描述】:

此方法接受一组字符串,然后删除该组偶数长度的所有字符串。 问题是我知道集合不按元素计数,所以我必须给我们一个迭代器,但是,如何从集合中删除特定的“元素”?

private static void removeEvenLength(Set<String> thing) {
    Iterator<String> stuff = thing.iterator();

    while (stuff.hasNext()) {
        String temp = stuff.next();
        if (temp.length() %2 == 0) {
            temp.remove(); // What do I do here?
        }
    }
}

【问题讨论】:

标签: java iterator set


【解决方案1】:

尝试使用迭代器

 stuff.remove();

【讨论】:

    【解决方案2】:
    private static void removeEvenLength(Set<String> thing) {
            thing.add("hi"); 
            thing.add("hello");
              Iterator<String> stuff = thing.iterator();
              System.out.println("set"+thing);
                while (stuff.hasNext()) {
                    String temp = stuff.next();
                    if (temp.length() %2 == 0) {
                        stuff.remove(); 
                    }
                }
                System.out.println("set"+thing); 
    }
    

    【讨论】:

      【解决方案3】:

      如果您使用的是 Java 8,您可以尝试以下方法:

      public static void removeEvenLength(final Set<String> set){
          set.stream().filter(string -> string.length() % 2 == 0).forEach(set::remove);
      }
      

      【讨论】:

        【解决方案4】:

        您不能这样做,因为 Set 类在您尝试在不使用迭代器的情况下从集合中删除元素时快速失败并抛出 ConcurrentModificationException。

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 2021-08-27
          • 2011-06-26
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2012-02-13
          相关资源
          最近更新 更多