Skip to content

Instantly share code, notes, and snippets.

@YukiYoshikawa
Created May 4, 2013 14:33
Show Gist options
  • Save YukiYoshikawa/5517676 to your computer and use it in GitHub Desktop.
Save YukiYoshikawa/5517676 to your computer and use it in GitHub Desktop.
package trial.yy.guava.client.collect;
import com.google.common.collect.HashMultiset;
import com.google.common.collect.Lists;
import com.google.common.collect.Multiset;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;
/**
* com.google.common.collect.Multisetを試すためのサンプル
* User: yy
*/
public class MultisetClient {
public static void main(String[] args) {
List<String> words = Lists.newArrayList("hello", "dog", "cat", "red", "hello", "hello", "dog", "blue", "blue");
// Multisetを使わずにList内に含まれる各単語の出現回数をカウントする場合
// 以下のような処理を使うことになるかな
Map<String, Integer> counts = new HashMap<>();
for (String word : words) {
Integer count = counts.get(word);
if (count == null) {
counts.put(word, 1);
} else {
counts.put(word, count + 1);
}
}
System.out.println("hello Number of occurrences: " + counts.get("hello"));
System.out.println("dog Number of occurrences: " + counts.get("dog"));
System.out.println("cat Number of occurrences: " + counts.get("cat"));
// Multisetを使って各単語の出現回数をカウントする場合は以下の通り
System.out.println("### Multiset.count execute");
// Multiset#countで各要素の個数をカウントしてみる
Multiset<String> wordMultiSet = HashMultiset.create(words);
System.out.println("hello Number of occurrences: " + wordMultiSet.count("hello"));
System.out.println("dog Number of occurrences: " + wordMultiSet.count("dog"));
System.out.println("cat Number of occurrences: " + wordMultiSet.count("cat"));
// iteratorを使って各要素にアクセスすると重複したものは複数回出力される
System.out.println("### Multiset.iterator execute");
for (String word : wordMultiSet) {
System.out.println(word);
}
// removeするとcountが1減る(元々2以上ある場合あcontainsはtrueを返す)
System.out.println("### Multiset.remove execute");
wordMultiSet.remove("hello");
System.out.println("hello contains: " + wordMultiSet.contains("hello"));
System.out.println("hello Number of occurrences: " + wordMultiSet.count("hello"));
// 削除する数を指定してremoveすることも可能
System.out.println("### Multiset.remove execute specifies the number");
wordMultiSet.remove("hello", 2);
System.out.println("hello contains: " + wordMultiSet.contains("hello"));
System.out.println("hello Number of occurrences: " + wordMultiSet.count("hello"));
// Multiset内の要素を格納したSetを返す(当然、返却されたSet内の要素の重複は無い)
System.out.println("### Multiset.elementSet execute");
Set<String> wordSet = wordMultiSet.elementSet();
for (String word : wordSet) {
System.out.println(word);
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment