Not logged in.  Login/Logout/Register | List snippets | | Create snippet | Upload image | Upload data

62
LINES

< > BotCompany Repo | #1031457 // MultiSetMapWithTopTen - MultiSetMap with a list of most "popular" keys [dev.]

JavaX fragment (include) [tags: use-pretranspiled]

Libraryless. Click here for Pure Java version (3385L/19K).

// analogous to OptimizedMultiSet
static class MultiSetMapWithTopTen<A, B> extends MultiSetMap<A, B> {
  // outer tree map for sorting
  // inner linked hash set for reproducability (HashSet ordering sucks)
  MultiSetMap<Int, A> byCount = multiSetMap_innerLinkedHashSet_outerRevTreeMap();

  *() {}
  *(bool useTreeMap) { super(useTreeMap); }
  *(MultiSetMap<A, B> map) { super(map); }
  *(Map<A, Set<B>> data) { super(data); }
  
  private void unindex(A key, Set<B> values) {
    if (nempty(values)) byCount.remove(l(values), key);
  }

  private void index(A key, Set<B> values) {
    if (nempty(values)) byCount.add(l(values), key);
  }

  bool put(A key, B value) { synchronized(data) {
    Set<B> set = data.get(key);
    unindex(key, set);
    if (set == null)
      data.put(key, set = _makeEmptySet());
    bool changed = set.add(value);
    index(key, set);
    if (!changed) false;
    ret true with ++size;
  }}

  void remove(A key) { synchronized(data) {
    Set<B> set = data.get(key);
    if (set == null) ret;
    size -= l(set);
    unindex(key, set);
    data.remove(key);
  }}

  void remove(A key, B value) { synchronized(data) {
    Set<B> set = data.get(key);
    if (set == null) ret;
    unindex(key, set);
    bool changed = set.remove(value);
    index(key, set);
    if (changed) {
      --size;
      if (set.isEmpty())
        data.remove(key);
    }
  }}

  void clear() { synchronized(data) {
    data.clear();
    byCount.clear();
    size = 0;
  }}

  // keys are the values in the byCount multimap
  ItIt<A> keysByPopularityIterator() {
    ret multiSetMapValuesIterator(byCount);
  }
}

Author comment

Began life as a copy of #1024456

download  show line numbers  debug dex  old transpilations   

Travelled to 4 computer(s): bhatertpkbcr, mqqgnosmbjvj, pyentgdyhuwx, vouqrxazstgt

No comments. add comment

Snippet ID: #1031457
Snippet name: MultiSetMapWithTopTen - MultiSetMap with a list of most "popular" keys [dev.]
Eternal ID of this version: #1031457/6
Text MD5: fc7ae6ecf52b24d01d998911aed339af
Transpilation MD5: 100b3e273920b5a705341f5db3fd2843
Author: stefan
Category: javax
Type: JavaX fragment (include)
Public (visible to everyone): Yes
Archived (hidden from active list): No
Created/modified: 2021-06-14 01:03:43
Source code size: 1682 bytes / 62 lines
Pitched / IR pitched: No / No
Views / Downloads: 149 / 295
Version history: 5 change(s)
Referenced in: [show references]