java数组相同元素个数_java String ArrayList数组是否有相同元素 以及相同元素个数...

问题:想要从俩个ArrayList中得到重复元素,已经重复的个数!

使用retainAll 此函数的作用是:

removeAll和retainAll 删除或保留ArrayList中包含Collection c中的的元素,这两个方法都依赖batchRemove(Collection> c,boolean complement)实现。

public class TestArrayList {

public static void main(String[] args) {

//初始化a1,a2,a3

ArrayList a1 = new ArrayList(Arrays.asList(1,2,3,4,5,6));

ArrayList a2 = new ArrayList(Arrays.asList(1,2,3,4));

ArrayList a3 = new ArrayList();

//把a1的元素全加到a3里

a3.addAll(a1);

//把a2,a3的共同元素保存到a3

a3.retainAll(a2);

System.out.println(a3);

}

}

在我的代码中的具体应用如下:

/**

* 此userId之前的用户加入了此eventId的用户中。有多少是他的关注者

* @param eventId

* @param userId

* @return

* @throws Exception

*/

public static int GetFollowingCountInThisEvent(String userId,String eventId) throws Exception

{

/*String eventId;String userId;

eventId ="18177707";

userId = "54172324";*/

//第一步:得到用户eventId的所有participants

ArrayList beforeUserArrayList = GetParticipantsByEventId(userId, eventId);

//第二步: 得到用户userId的所有following

System.out.println("开始获取用户的FollowingUser");

ArrayList userFollowingArralyList = CollectUserInfo.getUserFollowingUserByUserId(userId) ;

//第三步: 俩个ArrayList中重复的人数:

ArrayList userCommonArrayList = new ArrayList();

userCommonArrayList.addAll(beforeUserArrayList);

userCommonArrayList.retainAll(userFollowingArralyList);

for(String a : userCommonArrayList){

System.out.println("共同的用户为"+a);

}

return userCommonArrayList.size();

}

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值