-
Notifications
You must be signed in to change notification settings - Fork 0
Guava
illyfrancis edited this page Jul 18, 2013
·
14 revisions
- Type of collection
- Can it have duplicates?
- Is ordering significant? (for equals())
- Iteration order
- insertion-ordered? (Linked list) comparator-ordered? (Tree) user-ordered? (Array)
- something else well-defined?
- or it just doesn't matter?
In general, the first two determine the interface type, and the third tends to influce your choice of implementation
- Set: unordered equality, no dups
- List: ordered equauality, can have dups
Ordered?
Y N
Dups? +--------------+----------+
Y | List | Multiset |
+--------------+----------+
N | (UniqueList) | Set |
+--------------+----------+
- == Bag
- use cases,
- hand of cards, compare same hands
- are these Lists equal, ignoring order?
- histograms, what distinct tags am I using on my blog, and how many times do I use each one?
Map<String, Integer> tags
= new HashMap<String, Integer>();
for (BlogPost post : getAllBlogPosts()) {
for (String tag: post.getTags()) {
int value = tags.containsKey(tag) ? tags.get(tag) : 0;
tags.put(tag, value + 1);
}
}
- distinct tags:
tags.keySet() - count for "java" tag:
tags.containsKey("java") ? tags.get("java") : 0; - total count:
// oh crap... - Java tutorial shows proper way of doing this!!! (have a look)
Multiset<String> tags = HashMultiset.create();
for (BlogPost post : getAllBlogPosts()) {
tags.addAll(post.getTags())
}
- distinct tags:
tags.elementSet(); - count for "java" tag:
tags.count("java") - total count:
tags.size()
- if need to remove/decrement? (Multiset supports it)
- concurrency? (instead of locking the entire map, use ConcurrentMultiset)
- Everything from collection plus
- count, add, remove, setCount, etc