原因:
Collectors.groupingBy分組后默認返回HashMap類型,HashMap是無序的
解決:
將HashMap類型修改為LinkedHashMap即可
示例:
newList = list .stream() .sorted(Comparator.comparing(Student::getSage)) .collect(Collectors.groupingBy(Student::getSage, LinkedHashMap::new, Collectors.toList()));
-- Collectors.groupingBy 觀看源碼可知
-- Student::getSage (Function<? super T, ? extends K> classifier)解釋:根據字段進行分組
-- LinkedHashMap::new (Supplier<M> mapFactory)解釋:分組最后用什么容器保存返回
-- Collectors.toList() (Collector<? super T, A, D> downstream)解釋:收集分類的結果的收集器