Multiset Implementation in Java
This post will discuss how to implement a Multiset in Java.
A Multiset is a collection similar to a set that doesn’t guarantee any particular ordering on its elements, but it can accommodate duplicate elements, unlike Set. It supports duplicates by maintaining a count of the total number of occurrences of each element in the collection. Counting the frequency of elements is a very common operation in Java. We can use MultiSet to efficiently find the most frequent letter in a file or sort a limited range array.
We know that Java doesn’t provide Multiset implementation, so programmers often switch to HashMap to store the total number of times each key occurs. Although both Google Guava library and Apache Commons Collections provide Multiset implementation, wouldn’t it be great to implement our own Multiset class in Java?
Well, writing a Multiset class is actually very simple in Java. Following is a simple implementation of the Multiset class in Java that uses two lists – one to store the distinct elements and another to store their counts. Since list is used, the time complexity for most operations is linear in terms of the total number of distinct elements. A hash table is recommended over a list for optimal constant-time operations.
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 |
import java.util.*; import java.util.function.Consumer; import java.util.stream.Collectors; /* A class representing a Mutable Multiset */ class Multiset<E> { /* List to store distinct values */ private List<E> values; /* List to store counts of distinct values */ private List<Integer> frequency; private final String ERROR_MSG = "Count cannot be negative: "; /* Constructor */ public Multiset() { values = new ArrayList<>(); frequency = new ArrayList<>(); } /** * Adds an element to this multiset specified number of times * * @param `element` The element to be added * @param `count` The number of times * @return The previous count of the element */ public int add(E element, int count) { if (count < 0) { throw new IllegalArgumentException(ERROR_MSG + count); } int index = values.indexOf(element); int prevCount = 0; if (index != -1) { prevCount = frequency.get(index); frequency.set(index, prevCount + count); } else if (count != 0) { values.add(element); frequency.add(count); } return prevCount; } /** * Adds specified element to this multiset * * @param `element` The element to be added * @return true always */ public boolean add(E element) { return add(element, 1) >= 0; } /** * Adds all elements in the specified collection to this multiset * * @param `c` Collection containing elements to be added * @return true if all elements are added to this multiset */ boolean addAll(Collection<? extends E> c) { for (E element: c) { add(element, 1); } return true; } /** * Adds all elements in the specified array to this multiset * * @param `arr` An array containing elements to be added */ public void addAll(E... arr) { for (E element: arr) { add(element, 1); } } /** * Performs the given action for each element of the Iterable, * including duplicates * * @param `action` The action to be performed for each element */ public void forEach(Consumer<? super E> action) { List<E> all = new ArrayList<>(); for (int i = 0; i < values.size(); i++) { for (int j = 0; j < frequency.get(i); j++) { all.add(values.get(i)); } all.forEach(action); } } /** * Removes a single occurrence of the specified element from this multiset * * @param `element` The element to removed * @return true if an occurrence was found and removed */ public boolean remove(Object element) { return remove(element, 1) > 0; } /** * Removes a specified number of occurrences of the specified element * from this multiset * * @param `element` The element to removed * @param `count` The number of occurrences to be removed * @return The previous count */ public int remove(Object element, int count) { if (count < 0) { throw new IllegalArgumentException(ERROR_MSG + count); } int index = values.indexOf(element); if (index == -1) { return 0; } int prevCount = frequency.get(index); if (prevCount > count) { frequency.set(index, prevCount - count); } else { values.remove(index); frequency.remove(index); } return prevCount; } /** * Check if this multiset contains at least one occurrence of the * specified element * * @param `element` The element to be checked * @return true if this multiset contains at least one occurrence * of the element */ public boolean contains(Object element) { return values.contains(element); } /** * Check if this multiset contains at least one occurrence of each element * in the specified collection * * @param `c` The collection of elements to be checked * @return true if this multiset contains at least one occurrence * of each element */ public boolean containsAll(Collection<?> c) { return values.containsAll(c); } /** * Update the frequency of an element to the specified count or * add element to this multiset if not present * * @param `element` The element to be updated * @param `count` The new count * @return The previous count */ public int setCount(E element, int count) { if (count < 0) { throw new IllegalArgumentException(ERROR_MSG + count); } if (count == 0) { remove(element); } int index = values.indexOf(element); if (index == -1) { return add(element, count); } int prevCount = frequency.get(index); frequency.set(index, count); return prevCount; } /** * Find the frequency of an element in this multiset * * @param `element` The element to be counted * @return The frequency of the element */ public int count(Object element) { int index = values.indexOf(element); return (index == -1) ? 0 : frequency.get(index); } /** * @return A view of the set of distinct elements in this multiset */ public Set<E> elementSet() { return values.stream().collect(Collectors.toSet()); } /** * @return true if this multiset is empty */ public boolean isEmpty() { return values.size() == 0; } /** * @return Total number of elements in this multiset, including duplicates */ public int size() { int size = 0; for (Integer i: frequency) { size += i; } return size; } @Override public String toString() { StringBuilder sb = new StringBuilder("["); for (int i = 0; i < values.size(); i++) { sb.append(values.get(i)); if (frequency.get(i) > 1) { sb.append(" x ").append(frequency.get(i)); } if (i != values.size() - 1) { sb.append(", "); } } return sb.append("]").toString(); } } class Main { // Multiset implementation in Java public static void main(String[] args) { Multiset<String> multiset = new Multiset(); multiset.add("USA"); multiset.add("Japan", 2); multiset.addAll("India", "China"); multiset.addAll(Arrays.asList("USA", "India", "China", "Japan")); System.out.println(multiset); multiset.remove("China"); multiset.remove("Japan", 2); System.out.println(multiset); multiset.setCount("USA", 4); multiset.setCount("Japan", 5); multiset.setCount("Mexico", 3); multiset.setCount("China", 0); System.out.println(multiset); } } |
Output:
[USA x 2, Japan x 3, India x 2, China x 2]
[USA x 2, Japan, India x 2, China]
[USA x 4, Japan x 5, India x 2, Mexico x 3]
That’s all about Multiset implementation in Java.
Also See:
References: Multiset (Guava: Google Core Libraries for Java 23.0 API)
Thanks for reading.
To share your code in the comments, please use our online compiler that supports C, C++, Java, Python, JavaScript, C#, PHP, and many more popular programming languages.
Like us? Refer us to your friends and support our growth. Happy coding :)