Java8之stream流的分組排序
阿新 • • 發佈:2021-10-06
關於Java8的stream流,這裡不講groupBy分組,也不講sort排序,這些都是很基礎的用法,可以自行百度。
這裡說一種業務場景,對於一些人(姓名,地址,建立時間),要求按地址將他們分組,同時要求越晚被建立的人,所在的分組越靠前。
直接上People類:
import lombok.AllArgsConstructor; import lombok.Data; @Data @AllArgsConstructor public class People { private String name; private String address; private Long createTime; }
然後是分組排序程式碼:
public static void main(String[] args) { long time = 1L; List<People> list = new ArrayList<>(); list.add(new People("曹丕", "魏", time++)); list.add(new People("關羽", "蜀", time++)); list.add(new People("劉備", "蜀", time++)); list.add(new People("小喬", "吳", time++)); list.add(new People("周瑜", "吳", time++)); list.add(new People("曹操", "魏", time++)); Map<String, List<People>> collect = list.stream() .filter(d -> d != null && d.getAddress() != null) .sorted(Comparator.comparingLong(People::getCreateTime).reversed()) .collect(Collectors.groupingBy(People::getAddress, LinkedHashMap::new, Collectors.toList())); for (Map.Entry<String, List<People>> entry : collect.entrySet()) { System.out.println(entry.getKey() + "\t" + entry.getValue()); } }
最後是執行結果:
魏 [People(name=曹操, address=魏, createTime=6), People(name=曹丕, address=魏, createTime=1)]
吳 [People(name=周瑜, address=吳, createTime=5), People(name=小喬, address=吳, createTime=4)]
蜀 [People(name=劉備, address=蜀, createTime=3), People(name=關羽, address=蜀, createTime=2)]
那麼如果按照題目要求,這個時候,我再加個“蜀國”人,那麼這個人所在分組就應該放到第一的位置
long time = 1L;
List<People> list = new ArrayList<>();
list.add(new People("曹丕", "魏", time++));
list.add(new People("關羽", "蜀", time++));
list.add(new People("劉備", "蜀", time++));
list.add(new People("小喬", "吳", time++));
list.add(new People("周瑜", "吳", time++));
list.add(new People("曹操", "魏", time++));
list.add(new People("張飛", "蜀", time++));
執行後結果如下,發現最後新增的“張飛”所在的“蜀”分類,已經放到了第一的位置:
蜀 [People(name=張飛, address=蜀, createTime=7), People(name=劉備, address=蜀, createTime=3), People(name=關羽, address=蜀, createTime=2)]
魏 [People(name=曹操, address=魏, createTime=6), People(name=曹丕, address=魏, createTime=1)]
吳 [People(name=周瑜, address=吳, createTime=5), People(name=小喬, address=吳, createTime=4)]
© 版權宣告
文章版權歸作者所有,歡迎轉載,但必須給出原文連結,否則保留追究法律責任的權利
THE END