iT邦幫忙

0

groupingBy 排序問題

  • 分享至 

  • twitterImage

今天讀書遇到幾個問題
class Student {

String course, name, city;

public Student(String name, String course, String city) {
this.course = course;
this.name = name;
this.city = city;
}

public String toString() {
return course + ":" + name + ":" + city;
}

public String getCourse() {
return course;
}
}
List 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(src));
這個分組出來會顯示
Java EE
Java ME
不管我怎麼換順序
都是根據字母排序

但是換成下面的程式碼就不是照字母了
public class Country {

public enum Continent {
ASIA, EUROPE
}
String name;
Continent region;

public Country(String na, Continent reg) {
name = na;
region = reg;
}

public String getName() {
return name;
}

public Continent getRegion() {
return region;
}
}
List couList = Arrays.asList(
new Country("Japan", Country.Continent.ASIA),
new Country("Italy", Country.Continent.EUROPE), new Country("Germany", Country.Continent.EUROPE));
/System.out.println(couList);/
Map<Country.Continent, List> regionNames = couList.stream().
collect(Collectors.groupingBy(Country::getRegion,
Collectors.mapping(Country::getName, Collectors.toList())));
System.out.println(regionNames);

這串在不加入註解部分時
不管我怎麼換順序 都會是先丟進去的那個組放後面
也就是顯示ASIA在後 EUROPE在前
但是我加入註解後
一樣的程式卻會變成ASIA在前 EUROPE在後

那我該如何判斷使用groupingBy後 它的排序問題?
拜託各位高手幫忙解惑

圖片
  直播研討會
圖片
{{ item.channelVendor }} {{ item.webinarstarted }} |
{{ formatDate(item.duration) }}
直播中

1 個回答

1
海綿寶寶
iT邦大神 1 級 ‧ 2019-09-21 09:53:25
最佳解答

那我該如何判斷使用groupingBy後 它的排序問題?

groupingBy 就是「把相同的值 group 成一筆」,如此而已
跟排序沒有任何關係

而 Map 也不管你的順序
如果你要順序的話
請用LinkedHashMap

選我正解

chihyao iT邦新手 5 級 ‧ 2019-09-21 10:13:56 檢舉

那可以再請教一下候群組後面
它的排序是不是就是丟進去的順序?
像Italy就會排在Germany前面?

誠心奉勸你
要排序就自己呼叫函式去 sort
愛怎麼sort就怎麼sort
不要將希望寄託在佛系資料型態
「只要將資料填進去,不做動作,他就會照我要的順序自動排好」
/images/emoticon/emoticon10.gif

chihyao iT邦新手 5 級 ‧ 2019-09-21 21:16:08 檢舉

/images/emoticon/emoticon04.gif

我要發表回答

立即登入回答