---
# System prepended metadata

title: Collectors的groupingBy()
tags: [ocpjp]

---

# Collectors的groupingBy()
**Collectors的groupingBy()方法，告訴它要用哪個當作分組的鍵（Key），最後傳回的Map結果會以List作為值（Value）：**

```java=
public static void main(String[] args) {
        List<Student> stds = Arrays.asList(
                new Student ("Jessy", "Java ME", "Chicago"),
                new Student ("Helen", "Java EE", "Houston"),
                new Student ("Mark", "Java ME", "Chicago"));
        stds.forEach(System.out::println);
        System.out.println();
        
        Map<String,List<Student>> map = stds.stream().collect(Collectors.groupingBy(Student::getCourse));
        map.forEach((key,value)->System.out.println(key+","+value));
    }
```
**Console:**
```Console=
Java ME:Jessy:Chicago
Java EE:Helen:Houston
Java ME:Mark:Chicago

Java EE,[Java EE:Helen:Houston]
Java ME,[Java ME:Jessy:Chicago, Java ME:Mark:Chicago]
```

---
Example:
```java=
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;}
}
public class Test {
	public static void main(String[] args) {
		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);
				
	}
}
```
Console:
```=
{EUROPE=[Italy, Germany], ASIA=[Japan]}
```
:::warning
元素在Map物件中的順序，愈先建立群組的項目會排在愈後面，所以「ASIA」會排在「EUROPE」之後。元素在List物件中的順序就是原先集合物件的走訪順序，所以「Italy」在「Germany」之前。
:::
- [參考網站](https://magiclen.org/ocpjp-stream-lambda/)
###### tags: `ocpjp`