2015-12-29 78 views
1

我想刪除的情況下,從地圖鍵,如果該鍵的值是零(0)我能夠使用
map.values().removeAll(Collections.singleton(0l));

去實現它。
這是工作不錯,直到我用Map<String,Long>,但現在我們已經改變了實施Map<String,AtomicLong>現在這麼想的刪除其值是零,因爲我使用的是原子變量值的鍵。
一小段代碼上,我試着::刪除從地圖中原子的情況下,鍵值

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鍵沒有被刪除。任何人都可以提出解決方案,這將是非常有幫助的。
謝謝。

回答

1

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}

2

如果您使用的是Java8,那麼您可以使用一個removeIf方法。

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