Apache Commons Collections - Bag 接口



添加了新的接口来支持 Bag。Bag 定义了一个集合,它计算对象在集合中出现的次数。例如,如果一个 Bag 包含 {a, a, b, c},那么 getCount("a") 将返回 2,而 uniqueSet() 将返回唯一值。

接口声明

以下是 org.apache.commons.collections4.Bag<E> 接口的声明:

public interface Bag<E>
   extends Collection<E>

方法

Bag 接口的方法如下:

序号 方法及描述
1

boolean add(E object)

(违反)将指定对象的副本添加到 Bag 中。

2

boolean add(E object, int nCopies)

将指定对象的 nCopies 个副本添加到 Bag 中。

3

boolean containsAll(Collection<?> coll)

(违反)如果 Bag 包含给定集合中的所有元素,则返回 true,并考虑基数。

4

int getCount(Object object)

返回 Bag 中给定对象的出现次数(基数)。

5

Iterator<E> iterator()

返回整个成员集的迭代器,包括由于基数造成的副本。

6

boolean remove(Object object)

(违反)从 Bag 中移除给定对象的所有出现。

7

boolean remove(Object object, int nCopies)

从 Bag 中移除指定对象的 nCopies 个副本。

8

boolean removeAll(Collection<?> coll)

(违反)移除给定集合中表示的所有元素,并考虑基数。

9

boolean retainAll(Collection<?> coll)

(违反)移除 Bag 中不在给定集合中的任何成员,并考虑基数。

10

int size()

返回 Bag 中所有类型项目的总数。

11

Set<E> uniqueSet()

返回 Bag 中唯一元素的 Set。

继承的方法

此接口继承自以下接口:

  • java.util.Collectio。

Bag 接口示例

BagTester.java 的示例如下:

import org.apache.commons.collections4.Bag;
import org.apache.commons.collections4.bag.HashBag;

public class BagTester {
   public static void main(String[] args) {
      Bag<String> bag = new HashBag<>();
      //add "a" two times to the bag.
      bag.add("a" , 2);
      
      //add "b" one time to the bag.
      bag.add("b");
      
      //add "c" one time to the bag.
      bag.add("c");
      
      //add "d" three times to the bag.
      bag.add("d",3
      
      //get the count of "d" present in bag.
      System.out.println("d is present " + bag.getCount("d") + " times.");
      System.out.println("bag: " +bag);
      
      //get the set of unique values from the bag
      System.out.println("Unique Set: " +bag.uniqueSet());
      
      //remove 2 occurrences of "d" from the bag
      bag.remove("d",2);
      System.out.println("2 occurences of d removed from bag: " +bag);
      System.out.println("d is present " + bag.getCount("d") + " times.");
      System.out.println("bag: " +bag);
      System.out.println("Unique Set: " +bag.uniqueSet());
   }
}

输出

您将看到以下输出:

d is present 3 times.
bag: [2:a,1:b,1:c,3:d]
Unique Set: [a, b, c, d]
2 occurences of d removed from bag: [2:a,1:b,1:c,1:d]
d is present 1 times.
bag: [2:a,1:b,1:c,1:d]
Unique Set: [a, b, c, d]
广告