1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100
| public class StreamDemo5 { public static void main(String[] args) { List<Student> list = Arrays.asList( new Student("zhangsan1", 11, Sex.MALE, Gender.ONE), new Student("zhangsan2", 12, Sex.FEMAlE, Gender.TWO), new Student("zhangsan3", 13, Sex.MALE, Gender.THREE), new Student("zhangsan4", 14, Sex.FEMAlE, Gender.ONE), new Student("zhangsan5", 15, Sex.MALE, Gender.TWO), new Student("zhangsan6", 16, Sex.FEMAlE, Gender.THREE), new Student("zhangsan7", 17, Sex.MALE, Gender.ONE) );
List<Integer> ages = list.stream().map(Student::getAge).collect(Collectors.toList()); Set<Integer> agesSet1 = list.stream().map(Student::getAge).collect(Collectors.toSet()); Set<Integer> agesSet2 = list.stream().map(Student::getAge).collect(Collectors.toCollection(TreeSet::new)); System.out.println("所有学生的年龄是:" + ages);
IntSummaryStatistics studentList = list.stream().collect(Collectors.summarizingInt(Student::getAge)); System.out.println("学生的汇总信息是:" + studentList);
Map<Boolean, List<Student>> sex = list.stream().collect(Collectors.partitioningBy(s -> s.getSex() == Sex.MALE)); System.out.println("按照性别分块的结果是:" + sex);
Map<Gender, List<Student>> groups = list.stream().collect(Collectors.groupingBy(Student::getGender)); System.out.println("按照班级分组的结果是:" + groups);
Map<Gender, Long> nums = list.stream().collect(Collectors.groupingBy(Student::getGender, Collectors.counting())); System.out.println("每个班级的人数结果是:" + nums);
} }
class Student{ private String name; private Integer age; private Sex sex; private Gender gender;
public Student(String name, Integer age, Sex sex, Gender gender){ this.name = name; this.age = age; this.sex = sex; this.gender = gender; }
public String getName() { return name; }
public void setName(String name) { this.name = name; }
public Integer getAge() { return age; }
public void setAge(Integer age) { this.age = age; }
public Sex getSex() { return sex; }
public void setSex(Sex sex) { this.sex = sex; }
public Gender getGender() { return gender; }
public void setGender(Gender gender) { this.gender = gender; }
@Override public String toString() { return "Student{" + "name='" + name + '\'' + ", age=" + age + ", sex=" + sex + ", gender=" + gender + '}'; } }
enum Sex{ MALE, FEMAlE }
enum Gender{ ONE, TWO, THREE, FOUR, FIVE }
|