小弟程式菜雞,最近想考OCPJP
關於一些考古題
List<Student> stds = Arrays.asList(
new Student("Jessy", "Java ME", "Chicago"),
new Student("Helen", "Java EE", "Houston"),
new Student("Mark", "Java ME", "Chicago"));
stds.stream().collect(Collectors.groupingBy(Student::getCourse))
.forEach((src, res) -> System.out.println(res));
這時候不管new Student建立的順序怎麼換
都會顯示
Java EE
Java ME
但是換成
List<Country> couList = Arrays.asList(
new Country("Japan", Country.Continent.ASIA),
new Country("Italy", Country.Continent.EUROPE),
new Country("Germany", Country.Continent.EUROPE));
Map<Country.Continent, List<String>> regionNames =
couList.stream().
collect(Collectors.groupingBy(Country::getRegion
,Collectors.mapping(Country::getName,
Collectors.toList())));
System.out.println(regionNames);
此時顯示
EUROPE在前
ASIA在後
我自己測試是發現排列的順序變成先建立的放後面
所以該怎麼判斷這時候是使用怎樣排序的?
請各位高手幫我解惑QQ
作者:
ssccg (23)
2019-09-21 00:25:00groupingBy只會保留組內的順序(傳給downstream的順序)不會保留group間(Map的entry)的順序,就丟進Map了就看Map預設是用HashMap,Java EE在Java ME前面只是HashMap實作剛好造成這個結果而已,跟一開始的順序和字母序都無關換成groupingBy(..., LinkedHashMap::new, toList())就會跟一開始的順序一樣了基本上研究HashMap的key的順序是沒意義的...groupingBy會有個有mapFactory參數的就是讓你換想要的Map