Thursday 22 September 2011

Multisets

Guava part 1 - MultiMaps
Guava part 2 - BiMaps

Continuing this tour of Guava we get to the Multiset. I probably don't use this as much as Multimaps or Bimaps, but it certainly does have it's uses.

So what's a Multiset then?

Well as you might be able to guess it's a set that can hold multiple instances of the same object.

Isn't that just a List?

In Java there are two basic differences between Lists and Sets. Lists can hold duplicates of the same object, and Lists are always ordered. Sets can't hold duplicates, and there's no guarantee of order by the Set interface. (Some implementations - LinkedHashSet, SortedSet etc. - do of course provide a guaranteed order!)

So a Multiset occupies a sort of grey area between a List and a Set. Duplicates allowed, but no guaranteed order.

This collection is also sometimes called a Bag, in fact this is what Apache Commons Collections calls it's Mutlisets.

So what would I use one for?

The great thing about Multisets is they keep track of the counts of each particular object in the set. So you can use them for counting stuff.

Have you ever written code like the following:
Map<MyClass,Integer> objectCounts = new HashMap<MyClass,Integer>();

public void incrementCount(MyClass obj) {
    Integer count = objectCounts.get(obj);
    if (count == null) {
        objectCounts.put(obj,0);
    } else {
        objectCounts.put(obj,count++);
    }
}

public int getCount(MyClass obj) {
    Integer count = objectCounts.get(obj);
    if (count == null) {
        return 0;
    } else {
        return count;
    }
}
Bit unwieldy? Lets see how we might use a Multiset instead:
Multiset<MyClass> myMultiset = HashMultiset.create();

MyClass myObject = new MyClass();

myMultiset.add(myObject);
myMultiset.add(myObject);  // add it a second time.

System.out.println(myMultiset.count(myObject)); // 2

myMultiset.remove(myObject);
System.out.println(myMultiset.count(myObject)); // 1

As you can see that's much simpler! It's even possible to add/remove more than one object at at time
Multiset<MyClass> myMultiset = HashMultiset.create();

MyClass myObject = new MyClass();
myMultiset.add(myObject,5); // Add 5 copies of myObject

System.out.println(myMultiset.count(myObject)); // 5

myMultiset.remove(myObject,2); // remove 2 copies

System.out.println(myMultiset.count(myObject)); // 3
Pretty useful eh? As usual there's several implementations available depending on your requirements, and I recommend taking a look at the API: http://docs.guava-libraries.googlecode.com/git-history/v9.0/javadoc/com/google/common/collect/Multiset.html

45 comments:

Unknown said...

The best Real estate agent in Spain at our immoabroad site in Spain. Find and contact the most renowned agent in Spain and the best professionals agent.

laustan said...

The quantity of times a component has a place with the multiset is the variety of that part. The aggregate number of components in a multiset, including rehashed participations, is the cardinality of the multiset. For instance, in the multiset {a, a, b, b, b, c} the multiplicities of the individuals a, b, and c are separately 2, 3, and 1, and the cardinality of the multiset is 6. To recognize sets and multisets, a documentation that consolidates square sections is once in a while utilized: the multiset {2, 2, 3} can be spoken to as [2, 2, 3].[2] In multisets, as in sets and as opposed to tuples, the request of components is unimportant: The multisets {a, a, b} and {a, b, a} are equivalent.
best essay writing service

Unknown said...

I really like your modern stylish ideas which you have http://awriter.org/affordablepapers-com-review/ shared about manipulative. This blog provide extraordinary and exact information for which I was searching.

Paulina Cameron said...

I must thank the author for this brilliant blog. I have never seen someone being this good at programming. Keep up the good work! I reckon I had some problems with my computer’s programming and I failed to order an essay from the NYC Resume Services but now I know that having taken your advice I will never have such issues again.

writing tips said...

In mathematics, a multiset (or bag) is a generalization of the concept of a set that, unlike a set, allows multiple instances of the multiset's elements. For example, {a, a, b} and {a, b} are different multisets although they are the same set.
cheap assignment Writing Services

Alex said...

Great post.Duplex roller chain liked this blog.Keep it up

jeo john said...

Multi sets are explained very well.drum roller equipment interested in this post.Hope for more in future

Writer said...

Sometimes, it's more important to practice on programming tasks than write assignments. That's why students buy essays online.

mermaid said...

Thank you so much for your post.Its really awesome post.Thank you so much for your effort.list of courses in uk . Thank You

qbcustomerhelp said...

Quickbooks enterprise support Get Quickbooks Enterprise Support from certified Quickbooks Technical Team (+1 (833) 400-1001). We are available 24*7 for your service. Our Professional experts will resolve all issues of Quickbooks.(+1 (833) 400-1001)

qbcustomerhelp said...



Quickbooks enterprise support number Contact Quickbooks Enterprise Support Number to resolve any of your Quickbooks errors(+1 (833) 400-1001). Our Certified Quickbooks team is available 24*7. (+1 (833) 400-1001) to solve your Quickbooks issues.

Isabell Kiral said...

Programming is very useful for our online business and if you want to get success in life you should learn programming and develop a lot of softwares and earn a lot of money. Assignment writing services.

Matt Simons said...

A Multimap is a common method to associate keys with randomly many values. Guava’s Multimap framework creates it easy to handle a mapping from keys to multiple values. Best PhD Dissertation Help UK

Komal Dating Service said...

I have two wonderful dating services which carried out the best dating features in this aspect, there are many escorts companionship just see the website and know the above features in this aspect.
Delhi Call Girls
Delhi Escorts Service

Sonam Sharma said...

Looking for Classy Escorts in Delhi |Hot Call Girls in Delhi
Looking for Classy Escorts in Delhi is the most beautiful escort in Delhi and naturally very busty! Our sexy Delhi Escorts & Delhi Call girls are well trained to give best erotic/oil/nude/nuru/b2b/full satisfaction/oral massages Call us today! Don't miss out on this sexy opportunity !!
Call Girl in Delhi
Delhi Escorts

Shivani Sharma said...

Check the cost appropriately with escort office in ahmedabad escorts
jamnagar escorts
junagadh escorts
kheda escorts
kutch escorts
surat escorts

Shivani Sharma said...

These ahmedabad escorts can form into the life expectancy of the festival and cause you to feel good about them. You may take a great talk and revel in your experience with those escorts in the event that you utilize them and make them to go with you for the festival. You will not actually be worn out through it.
valsad escorts
vadodara escorts
rajkot escorts
surat escorts
surat escorts

Sonam Sharma said...

Thanks For sharing this useful info welcome to Vasant Kunj Escorts
I am Sonam, a recently single married horny who is looking For a safe and sane man to meet to satisfy my needs. Our services are open 24 hours With a friendly smile and a Seductive body with curves, 100% genuine.
Call Girls in Vasant Kunj
Vasant Kunj Escorts

Shivani Sharma said...

Celebrity and Models Classy and expert Escorts are prepared to work clients with enchanting moves. Awesome relational abilities, which makes it significantly simpler for outside customers to commit to Hollywood and Bollywood accompanies young ladies in ahmedabad escorts, keeps a rundown of vulnerabilities, to keep a mystery to their client.
palanpur escorts
ahwa escorts
banaskantha escorts
ahmedabad escorts
surat escorts

Shivani Sharma said...

Investigate lovely Female Escorts Ahmedabad and Enjoy the Ahmedabad Escort Services!
ahmedabad escorts
vadodara escorts
rajkot escorts
mount abu escorts
surat escorts

manjot singh said...

Thanks for the Valuable information.Really useful information. Thank you so much for sharing. It will help everyone.

SASVBA is recognized as the best machine learning training in Delhi. Whether you are a project manager, college student, or IT student, Professionals are the best machine learning institute in Delhi, providing the best learning environment, experienced machine learning instructors, and flexible training programs for the entire module.

FOR ORE INFO:

harryparker0123 said...

Hi Friends! My name is Harry parker, I am a professional writer. I have been engaged in this field for several years. I used to write blogs on the QuickBooks-related error in which I provide the most suitable fixing guidelines. When you face QuickBooks H202 Error or any other major/minor error while accessing QuickBooks, you can find my blog effective. I always mention simple and easy solutions so that you won’t confront any further issues while fixing your problem. I am active round the clock at the given helpline number, so you can also contact me anytime. I will suggest to you on phone call what will be better for you.

manjot singh said...

Thanks for the Valuable information.Really useful information. Thank you so much for sharing. It will help everyone.

Data analytics course in Delhi
FOR MORE INFO:

Canon Support said...

Have you ever encountered a canon printers not printingissue? If yes, then you are not alone. It is a common issue that most users face and try to fix it on their own. Admittedly, this error can pop up at any time of the day while printing. The basic and the foremost thing to check to resolve the issue is ink cartridge levels and paper tray. If you have insufficient ink levels, then your printer won’t print. Similarly, if you have no paper to print on, the printer won’t print. Check both of these things before you connect with the executives. We have been dealing with common printer problems for years and resolve these issues in no time. Connect with us to get it fixed.

wills flake said...

Best assignment experts help students with English Assignments like a pro. English Assignment Help

pihugupta said...

Thanks for sharing this post,Choosing the top courses after 12th will enable you to get selected by top brands. The rising competition has led to a disappointing situation among job-seekers. Therefore students should be much focused while stepping ahead to go with the specific courses.

pihugupta said...

Taking the online business to the next level might appear a big challenge but you can do it by exploring the cheapest Smm panel The online website of business works when people visit the website and place the orders after their satisfaction with the product available over there. But sometimes businesses could not reach potential customers due to a lack of a valid strategy, thus initiatives in this regard are vital to elevate the businesses.

denpro technologies said...

Best assignment expert is one of the promising names in the writing assignment market. Started the journey in 2012, we have come a long way in terms of delivering top-notch quality content. We specialize in financial assignment help homework, and coursework writing. Our Ph.D. professors promise on-time delivery at affordable rates.

Mumbaiescortshub said...


Turn all your imagination into reality by hiring the Best top-rated Mumbai Call Girls. Hire affordable Mumbai escorts to enjoy customize escort services.

Mumbai Escorts Services:
Mumbai Escorts | Mumbai Escorts Service |


Mumbai Sex Aunty Number | Phone Sex Mumbai | Mumbai Call Girl Whatsapp Number | Mumbai Call Girls Near Me |

Kevin Booth said...

Hey everyone. I am Mandy, a financial advisor and a cryptocurrency expert. Suppose your transaction hasn’t happened or you are facing any issue regarding it. Then, call the blockchain customer support number Customers who are in need of assistance may easily contact a team of highly qualified professionals through the Blockchain Support Phone Number.

Diyanka Call Girls said...

If you want some sensual call girls then contact us and meet with our naughty escorts. They are here to please you and make you satisfied with them.
Hot Escorts in Delhi
Horny Porn Star Wiki
Sexy Escorts in Pune
VIP Goa Escorts
Female Escorts in Delhi
Delhi Escorts Service
Naughty Escorts in Noida
Delhi Escort

Unknown said...

Thanks for sharing such valuable content post, I always appreciate efforts of quality information based content. For adult entertainment services in UK, you can visit https://www.liverpool-escorts.co.uk/

Tinakent 0ccations said...


this is a ayurvedic medicine for early discharge problem
AAO Full Form
best medicine for premature ejaculation in india
best medicine for premature ejaculation in india
best medicine for erectile dysfunction without side effects
natural male enhancement pills, tablets, medicine and capsule
male people ask which tablet is best for enhancement
Powerful Male Enhancement Supplements - Youtube
Finance and Inverstment Blog

Ramesh Sampangi said...

Enroll yourself in an advanced career program of Python through AI Patasala Python Training in Hyderabad.
Online Python Course in Hyderabad

Professional Course said...

I wanted to leave a little comment to support you and wish you the best of luck. We wish you the best of luck in all of your blogging endeavors.

Digital Marketing Institute in Bangalore

Deekshitha said...

Informative blog
best cyber security courses in kolkata

business analytics course in chennai with placement said...

Impressive. Your story always bring hope and new energy. Keep up the good work. Data Science Training in Vadodara

Sheetal Sharma said...

You can tell when your projects make a difference from the crowd. There's something unique about the projects. It appears to me that they are all amazing! the smm panel in india

Sheetal Sharma said...

You can tell when your projects make a difference from the crowd. There's something unique about the projects. It appears to me that they are all amazing! the best smm panel india

Sheetal Sharma said...

You can tell when your projects make a difference from the crowd. There's something unique about the projects. It appears to me that they are all amazing! the trusted smm panel

traininginstitute said...

Really impressed! Everything is very open and very clear clarification of issues. It contains truly facts. Your website is very valuable. Thanks for sharing.
full stack developer course with placement

Sonam Sinha said...

russian Models in delhi Russian Models in delhi

Chhavi Garg said...

Hello, I'm Chhavi Garg, The curvy Delhi Companion.
College model girl in Delhi

data science said...

This article will present a closer look at data science courses that give you a comprehensive look at the field. So let's get started.

data science course in borivali

Global Assignment Expert said...

Global Assignment Expert is an online platform that connects with students to overcome their assignment-related challenges. Global Assignment Help is one of the most popular assignment help service platforms for various reasons such as Expert Assistance, Time Management, Customized Solutions, Plagiarism-Free Work, and 24/7 Support. After completing the work the assignment goes through a rigorous quality check process and we ensure it meets the academic standards.