An example of java grouping and sorting items in a shopping cart is used in the project to sort the data in the shopping cart. I hope this article will help you.
Recently, we have a requirement to sort the items in the shopping cart. Items of the same activity must be displayed together.
The first method was to group commodities by activity before sorting them in the group.
It is found that this is a little troublesome and the performance is relatively low. After the leader reminds you to sort by activity first, so you can naturally group by activity.
In addition, jdk has its own algorithm for sorting sets. If you don't need to talk about it, go directly to the Code:
| The Code is as follows: |
Copy code |
/** * 1. sort by activity * 2. Sort items by product type (ordinary items, gifts, and combined sales) * 3. sort by product ID * 4. sort by the time when the shopping cart is added. * @ Param productColumnVolist * @ Return */ Private List <ProductColumnVo> productColumnSort (List <ProductColumnVo> productColumnVolist ){ Collections. sort (productColumnVolist, new Comparator <ProductColumnVo> (){ Public int compare (ProductColumnVo o1, ProductColumnVo o2 ){ If (StringUtils. isNotBlank (o1.getActiveID ()) & StringUtils. isBlank (o2.getActiveID ())){ // Active Display in front Return-1; } Else if (StringUtils. isBlank (o1.getActiveID ()) & StringUtils. isNotBlank (o2.getActiveID ())){ Return 1; } Else if (StringUtils. isNotBlank (o1.getActiveID ()) & StringUtils. isNotBlank (o2.getActiveID ())){ // Sort by activity Int activeCompareResult = o1.getActiveID (). compareTo (o2.getActiveID ()); If (activeCompareResult! = 0 ){ Return activeCompareResult; } } // Based on the product type (ordinary goods, gifts, combined sales from goods) Int productTypeCompareResult = o1.getProductType ()-o2.getProductType (); If (productTypeCompareResult = 0 ){ // Sort by product ID Int commodityTypeCompareResult = o1.getCommodityNo (). compareTo (o2.getCommodityNo ()); If (commodityTypeCompareResult = 0 ){ // Sort by the time when the shopping cart is added Return (o1.getAddDate (). before (o2.getAddDate ())? -1:1 ); } Else { Return commodityTypeCompareResult; } } Else { Return productTypeCompareResult; } } }); Return productColumnVolist; }
|
Simple enough.
The productType of the main product sold in combination is 0, and the productType of the product from the product is 3. The productType of the main item in the gift activity is 0, and the gift time is 1.
Note: The compare (a, B) method returns a negative integer, zero, or positive integer based on the first parameter smaller than, equal to, or greater than the second parameter. If the value is greater than 0, the order is adjusted. Otherwise, the Order is in the original order.
By the way, the implementation of Collections. sort is studied, which is a stable sorting. If the length of the set is less than 7, sort by direct insertion, and sort the rest by merging.