# Java 8 - 带有示例的 Stream Collectors 类

> 原文： [https://beginnersbook.com/2017/10/java-8-stream-collectors-class-with-examples/](https://beginnersbook.com/2017/10/java-8-stream-collectors-class-with-examples/)

收集器是[最终类](https://beginnersbook.com/2014/07/final-keyword-java-final-variable-method-class/)，它扩展了 Object 类。在本教程中，我们将看到使用 [lambda 表达式](https://beginnersbook.com/2017/10/java-lambda-expressions-tutorial-with-examples/)， [Java Streams](https://beginnersbook.com/2017/10/java-8-stream-tutorial/) 和 Java 8 的其他新功能的 Java Stream 收集器类的示例。

```java
java.lang.Object
   |
   |___java.util.stream.Collectors
```

## Java - Stream Collectors groupingBy 和计数示例

在此示例中，我们使用 Collectors 类的 groupingBy（）方法对列表的元素进行分组，并打印列表中每个元素的出现次数。

```java
import java.util.Arrays;
import java.util.List;
import java.util.Map;
import java.util.function.Function;
import java.util.stream.Collectors;

public class Example {

   public static void main(String[] args) {

      List<String> names =
          Arrays.asList("Jon", "Ajeet", "Steve",
             "Ajeet", "Jon", "Ajeet");

      Map<String, Long> map =
      names.stream().collect(
          Collectors.groupingBy(
             Function.identity(), Collectors.counting()
          )
      );

      System.out.println(map);

   }
}
```

输出：

```java
{Steve=1, Jon=2, Ajeet=3}
```

## Java - Stream Collector 将数据提取为 List 的示例

```java
import java.util.stream.Collectors;  
import java.util.List;  
import java.util.ArrayList;  
class Student{  
   int id;     
   String name;    
   int age;         
   public Student(int id, String name, int age) {  
        this.id = id;    
        this.name = name;         
        this.age = age;     
   } 
}  
public class Example {  
   public static void main(String[] args) {    
      List<Student> studentlist = new ArrayList<Student>();   
      //Adding Students      
      studentlist.add(new Student(11,"Jon",22));      
      studentlist.add(new Student(22,"Steve",18));        
      studentlist.add(new Student(33,"Lucy",22));        
      studentlist.add(new Student(44,"Sansa",23));         
      studentlist.add(new Student(55,"Maggie",18));                  
      //Fetching student names as List       
      List<String> names = studentlist.stream() 
                                   .map(n->n.name) 
                                   .collect(Collectors.toList());
      System.out.println(names);         
   }  
}
```

Output:

```java
[Jon, Steve, Lucy, Sansa, Maggie]
```

## Java 收集器示例 - 将数据收集为集合

在这个例子中，我们将学生列表转换为[流](https://beginnersbook.com/2017/10/java-8-stream-tutorial/)，然后我们应用 [Java Stream 过滤器](https://beginnersbook.com/2017/10/java-8-stream-filter/)从流中获取所选记录，之后我们将转换该流使用 Collectors.toSet（）方法设置。

```java
import java.util.stream.Collectors;  
import java.util.List;  
import java.util.Set; 
import java.util.ArrayList;  
class Student{    
   int id;     
   String name;  
   int age;           
   public Student(int id, String name, int age) {   
       this.id = id;         
       this.name = name;       
       this.age = age;      
   } 
}  
public class Example {     
   public static void main(String[] args) {       
      List<Student> studentlist = new ArrayList<Student>();       
      //Adding Students        
      studentlist.add(new Student(11,"Jon",22));         
      studentlist.add(new Student(22,"Steve",18));         
      studentlist.add(new Student(33,"Lucy",22));         
      studentlist.add(new Student(44,"Sansa",23));         
      studentlist.add(new Student(55,"Maggie",18));                  
      //Fetching student data as a Set       
      Set<Student> students = studentlist.stream()
                           .filter(n-> n.id>22)
                           .collect(Collectors.toSet());
      //Iterating Set       
      for(Student stu : students) { 
         System.out.println(stu.id+" "+stu.name+" "+stu.age); 
      }           
   } 
}
```

Output:

```java
44 Sansa 23
33 Lucy 22
55 Maggie 18
```

## Java 收集器示例 - 使用 averageInt（）方法获取学生的平均年龄

```java
import java.util.stream.Collectors;  
import java.util.List;  
import java.util.ArrayList; 
class Student{  
   int id;   
   String name;   
   int age;
   public Student(int id, String name, int age) {  
      this.id = id;   
      this.name = name; 
      this.age = age;  
   } 
}  
public class Example {  
   public static void main(String[] args) {  
      List<Student> studentlist = new ArrayList<Student>();  
      //Adding Students  
      studentlist.add(new Student(11,"Jon",22));   
      studentlist.add(new Student(22,"Steve",18));   
      studentlist.add(new Student(33,"Lucy",22));   
      studentlist.add(new Student(44,"Sansa",23));   
      studentlist.add(new Student(55,"Maggie",18));
      //Getting the average Age 
      Double avgAge = studentlist.stream()   
          .collect(Collectors.averagingInt(s->s.age));  
      System.out.println("Average Age of Students is: "+avgAge);
   }  
}
```

Output:

```java
Average Age of Students is: 20.6
```

我已经展示了 Java Collectors 类的极少数方法的例子。要获得完整的方法列表，请参阅 javadoc： [Java 8 流收集器 - JavaDoc](https://docs.oracle.com/javase/8/docs/api/java/util/stream/Collectors.html)