1. 程式人生 > >java8 stream代替for迴圈 sort多欄位排序 group by多級排序

java8 stream代替for迴圈 sort多欄位排序 group by多級排序

List<MacTicket> list = new ArrayList();

Category ctg= new Category();

ctg.setType(1);//0商品,1銷售規格

ctg.setSort(2);

ctg.setInheritFlag(0);//0繼承屬性1非繼承屬性

ctg.setValueSort(1)

Category ctg1= new Category();

ctg1.setType(0);//0商品,1銷售規格

ctg1.setSort(1);

ctg1.setInheritFlag(1);//0繼承屬性1非繼承屬性

ctg1.setValueSort(2)

list.add(ctg);

list.add(ctg1);

                lista.stream().sorted(Comparator.comparing(Category::getSort()).thenComparing(Category::getValueSort())).collect(Collectors.groupingBy(fetchGroupInheritKey(mtg)),Collectors.groupingBy(fetchGroupTypeKey(mtg)));

private String fetchGroupInheritKey(Category ctg){
                if(inheritFlag==0){
                    return "inheritList";
                }else if(inheritFlag==1){
                    return "ownList";
                }else{
                    return "";
                }
                
            }

使用Comparator實現多欄位排序和多級分組,前面的sort排序會影響後面的groupBy分組後的list中的排序