Multiple indexes for a Java Collection - most basic solution?

后端 未结 14 1781
小鲜肉
小鲜肉 2020-11-29 22:08

I\'m looking for the most basic solution to create multiple indexes on a Java Collection.

Required functionality:

  • When a Value is removed, all index en
14条回答
  •  鱼传尺愫
    2020-11-29 22:49

    Google Collections LinkedListMultimap

    About your first requirement

    • When a Value is removed, all index entries associated with that value must be removed.

    I think There is neither a library nor a Helper that supports it.

    Here is how i have done by using LinkedListMultimap

    Multimap multimap = LinkedListMultimap.create();
    
    // Three duplicates entries
    multimap.put(1, "A");
    multimap.put(2, "B");
    multimap.put(1, "A");
    multimap.put(4, "C");
    multimap.put(1, "A");
    
    System.out.println(multimap.size()); // outputs 5
    

    To get your first requirement, a Helper can play a good job

    public static  void removeAllIndexEntriesAssociatedWith(Multimap multimap, V value) {
        Collection> eCollection = multimap.entries();
        for (Map.Entry entry : eCollection)
            if(entry.getValue().equals(value))
                eCollection.remove(entry);
    }
    

    ...

    removeAllIndexEntriesAssociatedWith(multimap, "A");
    
    System.out.println(multimap.size()); // outputs 2
    

    Google collections is

    • lightweight
    • Supported by Joshua Block (Effective Java)
    • Nice features as ImmutableList, ImmutableMap and so on

提交回复
热议问题