1. 程式人生 > >將兩個List合併為一個List(並集)+取交集

將兩個List合併為一個List(並集)+取交集

並集

List<Integer> questionerIdList = new ArrayList<Integer>();

List l1 = sysuserinfMapper.findSysuserIdsByrRealName(questionName);

List l2 = wechatinfMapper.selectWechatIdsByNickname(questionName);

questionerIdList.addAll(l1);
questionerIdList.addAll(l2);

                           //準備一個空的list,將兩個list新增進去

StringBuffer ids = new StringBuffer();

if(questionerIdList.size()==0||questionerIdList==null){
return 0;
 }else{

 for (int i = 0; i < questionerIdList.size(); i++) {
if (i != 0) {
ids.append(",");
}
ids.append(questionerIdList.get(i));
}

 }

                            //將list轉化為以,分隔開的形式的字串(1,2,3,4,5)

**********************************************************************************

**********

********************************************************************************************

Map params = new HashMap<>();

params.put("ids", ids.toString());

List<ConsultCustomer> cclist = consultCustomerMapper.selectConsultCustomersByCondition(params);

  //serviceimpl中呼叫mapper中方法,並將引數params傳進去

select * from 表 where 欄位  in (${ids})  

                            // mapper.xml  中sql語句

交集

@org.junit.Test
	public void add() throws Exception {

		List<Integer> l1 = new ArrayList<Integer>();
		List<Integer> l2 = new ArrayList<Integer>();
		List<Integer> l3 = new ArrayList<Integer>();
		List<Integer> l4 = new ArrayList<Integer>();
		
		l1.add(1);
		l1.add(2);
		l1.add(3);
		l1.add(4);
		l1.add(5);
		
		l2.add(1);
		l2.add(2);
		l2.add(3);
		
		l3.add(1);
		l3.add(3);
		l3.add(4);
		
		l4.add(1);
		l4.add(2);
		l4.add(3);
		l4.add(4);
		l4.add(5);
		l4.add(6);
		
		l2.retainAll(l1);
		l2.retainAll(l3);
		l2.retainAll(l4);
		
		System.out.println("----");
		System.out.println(l2);
		
	}
        l2.retainAll(l1);
        l2.retainAll(l3);
        l2.retainAll(l4);  之後的l2即為交集