【问题标题】:Removing key from Map in case of Atomic Values在原子值的情况下从 Map 中删除键
【发布时间】:2016-04-03 16:05:52
【问题描述】:

如果键的值为 zero(0),我想从地图中删除键,我可以使用
map.values().removeAll(Collections.singleton(0l));

来实现它。
在我使用 Map<String,Long> 之前它运行良好,但现在我们已将实现更改为 Map<String,AtomicLong> 现在它不会删除值为零,因为我使用原子变量作为值。
我试过的小代码sn-p ::

    Map<String, AtomicLong> atomicMap = new HashMap<String,AtomicLong>();
    atomicMap.put("Ron", new AtomicLong(0l));
    atomicMap.put("David", new AtomicLong(0l));
    atomicMap.put("Fredrick", new AtomicLong(0l));
    atomicMap.put("Gema", new AtomicLong(1l));
    atomicMap.put("Andrew", new AtomicLong(1l));    

    atomicMap.values().removeAll(Collections.singleton(new AtomicLong(0l)));

    System.out.println(atomicMap.toString());

输出为
{Ron=0, Fredrick=0, Gema=1, Andrew=1, David=0}

如您所见,值为 0 的键并未被删除。任何人都可以提出解决方案,这将有很大帮助。
谢谢。

【问题讨论】:

    标签: java dictionary concurrency atomic key-value


    【解决方案1】:

    如果要计算,则决定在值为零时删除。

    if (atomicMap.compute("Andrew", (k, v) ->  v.decrementAndGet()) == 0) {
    
          atomicMap.remove("Andrew");
    }
    

    【讨论】:

      【解决方案2】:

      AtomicLong 的两个实例永远不会相等。如果您查看AtomicLong,您会发现它永远不会覆盖equal() 方法。见Why are two AtomicIntegers never equal?

      您可以通过自己的自定义AtomicLong 实现来克服这个问题,该实现实现equals() 并使您的删除元素的策略起作用。

      public class MyAtomicLongExample {
      
          static class MyAtomicLong extends AtomicLong {
      
              private static final long serialVersionUID = -8694980851332228839L;
      
              public MyAtomicLong(long initialValue) {
                  super(initialValue);
              }
      
              @Override
              public boolean equals(Object obj) {
                  return obj instanceof MyAtomicLong && ((MyAtomicLong) obj).get() == get();
              }
          }
      
          public static void main(String[] args) {
              Map<String, MyAtomicLong> atomicMap = new HashMap<>();
              atomicMap.put("Ron", new MyAtomicLong(0l));
              atomicMap.put("David", new MyAtomicLong(0l));
              atomicMap.put("Fredrick", new MyAtomicLong(0l));
              atomicMap.put("Gema", new MyAtomicLong(1l));
              atomicMap.put("Andrew", new MyAtomicLong(1l));    
      
              atomicMap.values().removeAll(Collections.singleton(new MyAtomicLong(0l)));
      
              System.out.println(atomicMap);
          }
      
      }
      

      这将打印{Gema=1, Andrew=1}

      【讨论】:

        【解决方案3】:

        如果您使用的是 Java8,则可以使用 removeIf 方法。

        atomicMap.values().removeIf(x -> x.get() == 0L);
        // Prints {Gema=1, Andrew=1}
        

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 2012-09-18
          • 2019-10-02
          • 2023-04-01
          • 1970-01-01
          • 2011-07-12
          • 2014-11-10
          • 1970-01-01
          • 1970-01-01
          相关资源
          最近更新 更多