public static void main(String[] args) {
List list = Lists.newArrayList();
list.add(new Student("測試", "男", 18));
list.add(new Student("開發", "男", 20));
list.add(new Student("運維", "女", 19));
list.add(new Student("DBA", "女", 22));
list.add(new Student("營運", "男", 24));
list.add(new Student("産品", "女", 21));
list.add(new Student("經理", "女", 25));
list.add(new Student("産品", "女", 21));
//求性别為男的學生集合
List l1 = list.stream().filter(student -> student.sex.equals("男")).collect(toList());
//map的key值true為男,false為女的集合
Map> map = list.stream().collect(partitioningBy(student -> student.getSex().equals("男")));
//求性别為男的學生總歲數
Integer sum = list.stream().filter(student -> student.sex.equals("男")).mapToInt(Student::getAge).sum();
//按性别進行分組統計人數
Map map = list.stream().collect(Collectors.groupingBy(Student::getSex, Collectors.summingInt(p -> 1)));
//判斷是否有年齡大于25歲的學生
boolean check = list.stream().anyMatch(student -> student.getAge() > 25);
//擷取所有學生的姓名集合
List l2 = list.stream().map(Student::getName).collect(toList());
//求所有人的平均年齡
double avg = list.stream().collect(averagingInt(Student::getAge));
//求年齡最大的學生
Student s = list.stream().reduce((student, student2) -> student.getAge() > student2.getAge() ? student:student2).get();
Student stu = list.stream().collect(maxBy(Comparator.comparing(Student::getAge))).get();
//按照年齡從小到大排序
List l3 = list.stream().sorted((s1, s2) -> s1.getAge().compareTo(s2.getAge())).collect(toList());
//求年齡最小的兩個學生
List l4 = l3.stream().limit(2).collect(toList());
//擷取所有的名字,組成一條語句
String str = list.stream().map(Student::getName).collect(Collectors.joining(",", "[", "]"));
//擷取年齡的最大值、最小值、平均值、求和等等
IntSummaryStatistics intSummaryStatistics = list.stream().mapToInt(Student::getAge).summaryStatistics();
System.out.println(intSummaryStatistics.getMax());
System.out.println(intSummaryStatistics.getCount());
}
@Data
@AllArgsConstructor
static class Student{
String name;
String sex;
Integer age;
}
最後給大家說一個并行化流操作parallelStream(),跟stream()的用法一樣。使用parallelStream就能立即獲得一個擁有并行能力的流,利用好并行化非常重要。不過并不是所有的流計算都要使用并行化流操作,隻有當計算機是多核并且集合資料量較大(超過一萬)的時候使用并行化流操作可以提高效率。
影響性能的五要素:資料大小、源資料結構、值是否裝箱、可用的CPU數量以及處理每個元素所花的時間。