一、使用步骤
1.代码示例
代码如下:
public class CollectorTest {
public static void main(String[] args) {
List<Student> students = Arrays.asList(
new Student("小明", 10, Gender.MALE, Grade.ONE),
new Student("小光", 9, Gender.MALE, Grade.THREE),
new Student("小红", 8, Gender.FEMALE, Grade.TWO),
new Student("小李", 13, Gender.FEMALE, Grade.FOUR),
new Student("小白", 7, Gender.FEMALE, Grade.THREE),
new Student("小美", 13, Gender.MALE, Grade.ONE),
new Student("小治", 13, Gender.FEMALE, Grade.THREE),
new Student("小灵", 9, Gender.FEMALE, Grade.TWO),
new Student("小流", 6, Gender.MALE, Grade.ONE),
new Student("小杨", 6, Gender.MALE, Grade.ONE),
new Student("小张", 14, Gender.FEMALE, Grade.FOUR),
new Student("小花", 13, Gender.MALE, Grade.FOUR));
//收集器实现年龄列表
List<Integer> ageList = students.stream().map(Student::getAge).collect(Collectors.toList());
System.out.println(ageList);
//收集器实现年龄去重列表
Set<Integer> ageSet = students.stream().map(Student::getAge).collect(Collectors.toSet());
System.out.println(ageSet);
//收集器收集到指定集合数据类型
ArrayList<Integer> ageArrayList = students.stream().map(Student::getAge).collect(Collectors.toCollection(ArrayList::new));
System.out.println(ageArrayList);
//收集器获取汇总信息
IntSummaryStatistics ageSummary = students.stream().collect(Collectors.summarizingInt(Student::getAge));
System.out.println(ageSummary);
Map<Boolean, List<Student>> collectToPart = students.stream().collect(Collectors.partitioningBy(x -> x.getGender() == Gender.MALE));
// System.out.println(collectToPart);
Map<Grade, List<Student>> groupByGrade = students.stream().collect(Collectors.groupingBy(Student::getGrade));
System.out.println(groupByGrade);
Map<Grade, Long> collect = students.stream().collect(Collectors.groupingBy(Student::getGrade, Collectors.counting()));
System.out.println(collect);
Map<Grade, Double> collect1 = students.stream().collect(Collectors.groupingBy(Student::getGrade, Collectors.averagingInt(Student::getAge)));
System.out.println(collect1);
}
}