關(guān)于Lists.partition集合分組使用以及注意事項(xiàng)
1.介紹
Lists.partition是com.google.common.collect包下的一個(gè)方法。
作用是將目標(biāo)集合按照傳入的size分組。
2.使用場(chǎng)景
一般用于固定大小的集合處理
比如:
我有兩百個(gè)商品類型,要求前一百個(gè)一種處理方式,后一百個(gè)一種處理方式。
3.用法
- pom文件
<dependency> <groupId>com.google.guava</groupId> <artifactId>guava</artifactId> <version>21.0</version> </dependency>
- 測(cè)試方法
public static void main(String[] args) { //需要進(jìn)行分組的集合 List<Integer> targetList = new ArrayList<>(); targetList.add(1); targetList.add(2); targetList.add(3); targetList.add(4); targetList.add(5); targetList.add(6); //集合分組。2代表 每?jī)蓚€(gè)分成一組。已知集合size=6,兩個(gè)一組即分為三組 List<List<Integer>> partition = Lists.partition(targetList, 2); System.out.println("切分后的數(shù)組,index【0】:"+partition.get(0)); System.out.println("切分后的數(shù)組,index【1】:"+partition.get(1)); System.out.println("切分后的數(shù)組,index【2】:"+partition.get(2)); }
- 結(jié)果
注意:
如果對(duì)也就是對(duì)子集合的操作會(huì)反映到原集合, 對(duì)原集合的操作也會(huì)影響子集合。
- 測(cè)試方法
public static void main(String[] args) { List<Integer> targetList = new ArrayList<>(); targetList.add(1); targetList.add(2); targetList.add(3); targetList.add(4); targetList.add(5); targetList.add(6); List<List<Integer>> partition = Lists.partition(targetList, 2); System.out.println("切分后的數(shù)組,index【0】:"+partition.get(0)); System.out.println("切分后的數(shù)組,index【1】:"+partition.get(1)); System.out.println("切分后的數(shù)組,index【2】:"+partition.get(2)); targetList.clear(); System.out.println("原集合大小"+targetList.size()); System.out.println("分組后集合大小"+partition.size()); }
- 結(jié)果
總結(jié)
以上為個(gè)人經(jīng)驗(yàn),希望能給大家一個(gè)參考,也希望大家多多支持腳本之家。
相關(guān)文章
SpringBoot整合Elasticsearch并實(shí)現(xiàn)CRUD操作
這篇文章主要介紹了SpringBoot整合Elasticsearch并實(shí)現(xiàn)CRUD操作,需要的朋友可以參考下2018-03-03springboot?jpa?實(shí)現(xiàn)返回結(jié)果自定義查詢
這篇文章主要介紹了springboot?jpa?實(shí)現(xiàn)返回結(jié)果自定義查詢方式,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。如有錯(cuò)誤或未考慮完全的地方,望不吝賜教2022-02-02SpringMVC在多線程下請(qǐng)求頭獲取失敗問題的解決方案
這篇文章主要介紹了我們就對(duì)多線程環(huán)境下使用SpringMVC中RequestContextHolder無(wú)法獲取請(qǐng)求的問題進(jìn)行了深入的分析,并針對(duì)相關(guān)問題給出了相應(yīng)的解決方案,需要的朋友可以參考下2024-08-08使用Java編寫一個(gè)圖片word互轉(zhuǎn)工具
這篇文章主要介紹了使用Java編寫一個(gè)PDF?Word文件轉(zhuǎn)換工具的相關(guān)資料,需要的朋友可以參考下2023-01-01