java面试题网

普通会员

483

帖子

9

回复

187

积分

楼主
发表于 2019-08-26 15:24:39 | 查看: 5020| 回复: 0

Guava Multiset接口

Guava Multiset接口

Multiset接口扩展设置有重复的元素,并提供了各种实用的方法来处理这样的元素在集合中出现。

接口声明

以下是com.google.common.collect.Multiset 接口的声明:

@GwtCompatible
public interface Multiset<E>
   extends Collection<E>

接口方法

Guava Multiset接口_www.wityx.com

方法继承

此接口继承从以下接口方法:

java.util.Collection

Multiset 示例

使用所选择的编辑器创建下面的java程序,比如说 C:/> Guava GuavaTester.java

import java.util.Iterator;
import java.util.Set;

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

public class GuavaTester {

   public static void main(String args[]){
      //create a multiset collection
      Multiset<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
      Set<String> set = multiset.elementSet();
      //display the elements of the set
      System.out.println("Set [");
      for (String s : set) {			
         System.out.println(s);		    
      }
      System.out.println("]");
      //display all the elements of the multiset using iterator
      Iterator<String> iterator  = multiset.iterator();
      System.out.println("MultiSet [");
      while(iterator.hasNext()){
         System.out.println(iterator.next());
      }
      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"));
   }	
}

验证结果

使用javac编译器编译如下类

C:Guava>javac GuavaTester.java

现在运行GuavaTester看到的结果

C:Guava>java GuavaTester

看到结果

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


文章来自www.wityx.com,转载请注明出处!原文地址http://www.wityx.com/post/1252_1_1.html

上一篇:Guava BiMap接口 下一篇:Guava集合工具
您需要登录后才可以回帖 登录 | 立即注册

java面试题网www.wuliaokankan.cnjava建站系统提供技术支持V2.1 网站地图 © 2016-2018