English | 简体中文 | 繁體中文 | Русский язык | Français | Español | Português | Deutsch | 日本語 | 한국어 | Italiano | بالعربية
Java ArrayList Grouping by the Same Attribute
Preface:
When querying a batch of data with SQL, you can use the SQL GROUP BY statement to group the data, but sometimes for performance considerations, GROUP BY is not used, and the data is first fetched out and then grouped in memory according to a certain attribute using code.
Code
public class SkuVo { private Long skuId; private String productName; private Long brandStoreSn; public SkuVo(Long skuId, String productName, Long brandStoreSn) { super(); this.skuId = skuId; this.productName = productName; this.brandStoreSn = brandStoreSn; } public Long getSkuId() { return skuId; } public void setSkuId(Long skuId) { this.skuId = skuId; } public String getProductName() { return productName; } public void setProductName(String productName) { this.productName = productName; } public Long getBrandStoreSn() { return brandStoreSn; } public void setBrandStoreSn(Long brandStoreSn) { this.brandStoreSn = brandStoreSn; } @Override public String toString() { return "SkuVo [skuId=" + skuId + ", productName=" + productName + ", brandStoreSn=" + brandStoreSn + "]"; } }
Assuming a batch of data is queried from the data and exists in the List<SkuVo>. Use an algorithm to group the List<SkuVo> by skuId, and those with the same skuId are grouped together.
Grouping Algorithm
public class TestArrayListGroupByKey { public static void main(String[] args) { /*1、Prepare Data**/ SkuVo sku1 = new SkuVo(1L,"p1"100L); SkuVo sku2 = new SkuVo(2L,"p2"101L); SkuVo sku3 = new SkuVo(3L,"p3"102L); SkuVo sku4 = new SkuVo(3L,"p4"103L); SkuVo sku5 = new SkuVo(2L,"p5"100L); SkuVo sku6 = new SkuVo(5L,"p6"100L); List<SkuVo> skuVoList = Arrays.asList(new SkuVo [] {sku1,sku2,sku3,sku4,sku5,sku6}); /*2、Grouping Algorithm**/ Map<Long, List<SkuVo>> skuIdMap = new HashMap<>(); for (SkuVo skuVo : skuVoList) { List<SkuVo> tempList = skuIdMap.get(skuVo.getSkuId()); /*If the data cannot be obtained, a new empty ArrayList will be created directly**/ if (tempList == null) { tempList = new ArrayList<>(); tempList.add(skuVo); skuIdMap.put(skuVo.getSkuId(), tempList); } else { /*If a certain sku has been stored before, data will be appended directly to the original List**/ tempList.add(skuVo); } } /*3、Traverse the map to verify the results**/ for(Long skuId : skuIdMap.keySet()){ System.out.println(skuIdMap.get(skuId)); } } }
The results are as follows
[SkuVo [skuId=1, productName=p1, brandStoreSn=100]] [SkuVo [skuId=2, productName=p2, brandStoreSn=101], SkuVo [skuId=2, productName=p5, brandStoreSn=100]] [SkuVo [skuId=3, productName=p3, brandStoreSn=102], SkuVo [skuId=3, productName=p4, brandStoreSn=103]] [SkuVo [skuId=5, productName=p6, brandStoreSn=100]]
From the output results, the data has been grouped according to skuId.
Thank you for reading, I hope it can help everyone, thank you for your support to this site!