Advertisement
i_love_rao_khushboo

java-multiset-implementation

Jan 28th, 2024
614
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 1.24 KB | None | 0 0
  1. static class Multiset<E> {
  2.         private NavigableMap<E, Integer> map;
  3.         int totalElements;
  4.  
  5.         public Multiset() {
  6.             map = new TreeMap<>();
  7.             totalElements = 0;
  8.         }
  9.  
  10.         public void add(E element) {
  11.             map.put(element, map.getOrDefault(element, 0) + 1);
  12.             totalElements += 1;
  13.         }
  14.  
  15.         public void remove(E element) {
  16.             int count = map.getOrDefault(element, 0);
  17.             if(count > 0) {
  18.                 map.put(element, count - 1);
  19.                 count -= 1;
  20.                 if(count == 0) {
  21.                     map.remove(element);
  22.                 }
  23.                 totalElements -= 1;
  24.             }
  25.         }
  26.  
  27.         public int count(E element) {
  28.             return map.getOrDefault(element, 0);
  29.         }
  30.  
  31.         public int size() {
  32.             return totalElements;
  33.         }
  34.  
  35.         public boolean isEmpty() {
  36.             return map.isEmpty();
  37.         }
  38.  
  39.         public E firstEntry() {
  40.             Map.Entry<E, Integer> entry = map.firstEntry();
  41.             return entry.getKey();
  42.         }
  43.  
  44.         public E lastEntry() {
  45.             Map.Entry<E, Integer> entry = map.lastEntry();
  46.             return entry.getKey();
  47.         }
  48.     }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement