📜  Apache Commons Collections-Bag接口

📅  最后修改于: 2020-11-18 08:22:01             🧑  作者: Mango


新接口已添加到支撑袋中。袋子定义了一个集合,该集合计算对象出现在集合中的次数。例如,如果Bag包含{a,a,b,c},则getCount(“ a”)将返回2,而uniqueSet()返回唯一值。

接口声明

以下是org.apache.commons.collections4.Bag 接口的声明-

public interface Bag
   extends Collection

方法

袋推断的方法如下-

Sr.No. Method & Description
1

boolean add(E object)

(Violation) Adds one copy of the specified object to the Bag.

2

boolean add(E object, int nCopies)

Adds nCopies copies of the specified object to the Bag.

3

boolean containsAll(Collection coll)

(Violation) Returns true if the bag contains all elements in the given collection, respecting cardinality.

4

int getCount(Object object)

Returns the number of occurrences (cardinality) of the given object currently in the bag.

5

Iterator iterator()

Returns an Iterator over the entire set of members, including copies due to cardinality.

6

boolean remove(Object object)

(Violation) Removes all occurrences of the given object from the bag.

7

boolean remove(Object object, int nCopies)

Removes nCopies copies of the specified object from the Bag.

8

boolean removeAll(Collection coll)

(Violation) Remove all elements represented in the given collection, respecting cardinality.

9

boolean retainAll(Collection coll)

(Violation) Remove any members of the bag that are not in the given collection, respecting cardinality.

10

int size()

Returns the total number of items in the bag across all types.

11

Set uniqueSet()

Returns a Set of unique elements in the Bag.

继承的方法

该接口从以下接口继承方法-

  • java.util.Collection

袋接口示例

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 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]