簡體   English   中英

分割ArrayList <ProductBean> 使用特定值

[英]Split ArrayList<ProductBean> using particular value

使用特定值分割ArrayList<ProductBean>問題

ArrayList<ProductBean> al =new ArrayList<ProductBean>(); 

這里ProductBean是其中包含幾個領域,如productId參數,產品名稱,productPrice,shopId等消氣與二傳手類

                           (productId, productName, productPrice, shopId)
                           -------------------------
 ProductBean s1=new ProductBean(101,"Pantene Shampoo","10 rs.",23);  
  ProductBean s2=new ProductBean(102,"Himalaya Fasewash","80 rs.",21);  
  ProductBean s2=new ProductBean(103,"Dettol Bath soap","30 rs.",25);  
  ProductBean s2=new ProductBean(104,"Dove Bath soap","30 rs.",25);  
  ProductBean s2=new ProductBean(105,"Santoor Bath soap","20 rs.",25);  
  //creating arraylist  
  ArrayList<ProductBean> al=new ArrayList<ProductBean>();  
  al.add(s1);//adding ProductBean class object  
  al.add(s2);  
  al.add(s3);  

ArrayList具有具有相同或不同shopId多個產品數據,這意味着假設我有5種不同產品,其中2個具有相同shopId產品具有不同的shopId。

現在,我想用不同的shopId分隔ArrayList ,如代碼段中所示,其中shopId為25,其余21、23為3,這將導致3個不同的arraylist

一種方法是使用HashMap

HashMap<Integer, ArrayList<ProductBean>> map = new HashMap<>();

然后添加具有ID的產品以映射為

map.put(id,list);//ArrayList<ProductBean>

通過從地圖獲取列表來更新相同ID的列表,然后為相同ID重新插入更新后的列表

如果您有很長的productbean列表, productbeanasynctsk完成所有這些productbean

您可以對流使用過濾操作,然后從原始數據中刪除新收集的列表值。

final List<ProductBean> first = al.stream()
        .filter(p -> p.getShopId().equals(25))
        .collect(Collectors.toList());
al.removeAll(first);

//repeate for other values you wish to split

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM