Guava提供了一個新集合類型Multiset,它能夠屢次添加相等的元素,且和元素順序無關。Multiset繼承於JDK的Cllection接口,而不是Set接口。java
Multiset主要方法介紹:this
package com.parry.guava.GuavaTest; import java.util.ArrayList; import java.util.List; import com.google.common.collect.HashMultiset; import com.google.common.collect.Multiset; public class MultisetTest { public static void main(String[] args) { String str = "this is a cat and that is a mice"; String[] strArr = str.split(" "); List<String> words = new ArrayList<String>(); for (String stmp : strArr) { words.add(stmp); } Multiset<String> wordMultiset = HashMultiset.create(); wordMultiset.addAll(words); //將不一樣的元素放在一個集合set中 for (String key : wordMultiset.elementSet()) { //查看指定元素的個數 System.out.println(key + "-->" + wordMultiset.count(key)); } System.out.println("-----向集合中添加元素-----"); //向集合中添加元素 wordMultiset.add("that"); for (String key : wordMultiset.elementSet()) { System.out.println(key + "-->" + wordMultiset.count(key)); } System.out.println("-----向集合中添加若干個元素-----"); //向集合中添加若干個元素 wordMultiset.add("and", 10); for (String key : wordMultiset.elementSet()) { System.out.println(key + "-->" + wordMultiset.count(key)); } System.out.println("-----向集合中移出一個元素-----"); //向集合中移出一個元素 wordMultiset.remove("that"); for (String key : wordMultiset.elementSet()) { System.out.println(key + "-->" + wordMultiset.count(key)); } System.out.println("-----向集合中移出若干個元素-----"); //向集合中移出若干個元素,若是元素的個數小於要移除的個數,則會把該元素移除光 wordMultiset.remove("and",10); for (String key : wordMultiset.elementSet()) { System.out.println(key + "-->" + wordMultiset.count(key)); } System.out.println("-----向集合中移出一個元素-----"); //向集合中移出一個元素 wordMultiset.remove("is"); for (String key : wordMultiset.elementSet()) { System.out.println(key + "-->" + wordMultiset.count(key)); } System.out.println("-----設定某一個元素的重複次數-----"); //設定某一個元素的重複次數 wordMultiset.setCount("and", 10); for (String key : wordMultiset.elementSet()) { System.out.println(key + "-->" + wordMultiset.count(key)); } System.out.println("-----設置複合元素的個數設爲新的重複次數-----"); //設置複合元素的個數設爲新的重複次數(條件是參數等於原來的元素個數) wordMultiset.setCount("and", 1,0); for (String key : wordMultiset.elementSet()) { System.out.println(key + "-->" + wordMultiset.count(key)); } System.out.println("-----刪除給定集合中的元素-----"); //刪除給定集合中的元素 wordMultiset.removeAll(words); for (String key : wordMultiset.elementSet()) { System.out.println(key + "-->" + wordMultiset.count(key)); } } }