Guava Collections - Multiset Interface

Multiset Interface

Multiset interface extends ‘Set’ to have duplicate elements, and provides various utility methods to deal with the occurrences of such elements in a set.

package org.fool.guava.collections;

import java.util.Set;

import com.google.common.collect.HashMultiset;
import com.google.common.collect.Multiset;

public class MultisetTest {
	public static void main(String[] args) {
		HashMultiset<String> multiset = HashMultiset.create();
		multiset.add("a");
		multiset.add("b");
		multiset.add("c");
		multiset.add("d");
		multiset.add("a");
		multiset.add("b");
		multiset.add("c");
		multiset.add("b");
		multiset.add("b");
		multiset.add("b");

		// print the occurrence of an element
		System.out.println("Occurrence of 'b' : " + multiset.count("b"));

		// print the total size of the multiset
		System.out.println("Total Size : " + multiset.size());

		// get the distinct elements of the multiset as set
		System.out.println("Set [");
		Set<String> set = multiset.elementSet();
		set.forEach(s -> System.out.println(s));
		System.out.println("]");

		// display all the elements of the multiset
		System.out.println("MultiSet [");
		multiset.forEach(ms -> System.out.println(ms));
		System.out.println("]");

		// display the distinct elements of the multiset with their occurrence
		// count
		System.out.println("MultiSet [");
		for (Multiset.Entry<String> entry : multiset.entrySet()) {
			System.out.println("Element: " + entry.getElement() + ", Occurrence(s): " + entry.getCount());
		}
		System.out.println("]");

		// remove extra occurrences
		multiset.remove("b", 2);
		// print the occurrence of an element
		System.out.println("Occurence of 'b' : " + multiset.count("b"));
	}
}

 output

Occurrence of 'b' : 5
Total Size : 10
Set [
a
b
c
d
]
MultiSet [
a
a
b
b
b
b
b
c
c
d
]
MultiSet [
Element: a, Occurrence(s): 2
Element: b, Occurrence(s): 5
Element: c, Occurrence(s): 2
Element: d, Occurrence(s): 1
]
Occurence of 'b' : 3

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值