Apache通用集合Bag接口

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

接口声明

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

public interface Bag<E>
   extends Collection<E>

Java

编号方法描述
1boolean add(E object)(冲突)将指定的对象到Bag的一个副本。
2boolean add(E object, int nCopies)将指定对象的nCopies副本添加到Bag中。
3boolean containsAll(Collection<?> coll)(冲突)如果包包含给定集合中的所有元素,并且尊重基数,则返回true
4int getCount(Object object)返回包中当前给定对象的出现次数(基数)。
5Iterator<E> iterator()在整个成员集上返回一个迭代器,包括由于基数而产生的副本。
6boolean remove(Object object)Bag中移除所有给定的对象。
7boolean remove(Object object, int nCopies)Bag中删除指定对象的nCopies副本。
8boolean removeAll(Collection<?> coll)删除给定集合中的所有元素,尊重基数。
9boolean retainAll(Collection<?> coll)移除不在给定集合中的所有Bag成员,尊重基数。
10int size()返回Bag中所有类型对象的总数。
11Set<E> uniqueSet()返回Bag中的一组唯一元素。

方法继承

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

  • java.util.Collection

Bag接口示例

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());
   }
}

Java

执行上面示例代码,得到以下结果 -

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]

  • 8
    点赞
  • 9
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

智慧浩海

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值