Commons-collections-bag

提供:Dev Guides
移動先:案内検索

Apache Commons Collections-バッグインターフェイス

サポートバッグに新しいインターフェイスが追加されました。 Bagは、コレクションにオブジェクトが出現する回数をカウントするコレクションを定義します。 たとえば、Bagに\ {a、a、b、c}が含まれる場合、getCount( "a")は2を返し、uniqueSet()は一意の値を返します。

インターフェイス宣言

以下は、org.apache.commons.collections4.Bag <E>インターフェースの宣言です-

public interface Bag<E>
   extends Collection<E>

方法

Sr.No. Method & Description
1

boolean add(E object)

(違反)指定されたオブジェクトの1つのコピーをバッグに追加します。

2

boolean add(E object, int nCopies)

指定されたオブジェクトのnCopiesコピーをBagに追加します。

3

boolean containsAll(Collection<?> coll)

(違反)カーディナリティを考慮して、バッグが指定されたコレクション内のすべての要素を含む場合、trueを返します。

4

int getCount(Object object)

現在バッグ内にある特定のオブジェクトのオカレンス数(カーディナリティ)を返します。

5

Iterator<E> iterator()

カーディナリティによるコピーを含む、メンバーのセット全体のイテレータを返します。

6

boolean remove(Object object)

(違反)指定されたオブジェクトのすべての出現をバッグから削除します。

7

boolean remove(Object object, int nCopies)

指定したオブジェクトのnCopiesコピーをバッグから削除します。

8

boolean removeAll(Collection<?> coll)

(違反)指定されたコレクションで表されるすべての要素を削除し、カーディナリティを尊重します。

9

boolean retainAll(Collection<?> coll)

(違反)特定のコレクションに含まれないバッグのメンバーを、カーディナリティを考慮して削除します。

10

int size()

すべてのタイプのバッグ内のアイテムの総数を返します。

11

Set<E> uniqueSet()

バッグ内の一意の要素のセットを返します。

継承されるメソッド

このインターフェイスは、次のインターフェイスからメソッドを継承します-

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