Java8之list.stream的常見使用例子

本博客系轉載,原文鏈接:https://blog.csdn.net/baidu_38083619/article/details/87891206
一個例子:

public static void main(String[] args) {
        List<Student> 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<Student> l1 = list.stream().filter(student -> student.sex.equals("男")).collect(toList());
        
        //map的key值true爲男,false爲女的集合
        Map<Boolean, List<Student>> map = list.stream().collect(partitioningBy(student -> student.getSex().equals("男")));
 
        //求性別爲男的學生總歲數
        Integer sum = list.stream().filter(student -> student.sex.equals("男")).mapToInt(Student::getAge).sum();
 
        //按性別進行分組統計人數
        Map<String, Integer> map = list.stream().collect(Collectors.groupingBy(Student::getSex, Collectors.summingInt(p -> 1)));
 
        //判斷是否有年齡大於25歲的學生
        boolean check = list.stream().anyMatch(student -> student.getAge() > 25);
 
        //獲取所有學生的姓名集合
        List<String> 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<Student> l3 = list.stream().sorted((s1, s2) -> s1.getAge().compareTo(s2.getAge())).collect(toList());
 
        //求年齡最小的兩個學生
        List<Student> 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數量以及處理每個元素所花的時間。
關於利用stream求和的一個例子,可以學習下這種用法:

package lambda;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

public class StreamTest {
    public static void main(String[] args) {
        List<List<String>> finalList = new ArrayList<>();
        finalList.add(new ArrayList<>(Arrays.asList("1", "2", "3", "4")));
        finalList.add(new ArrayList<>(Arrays.asList("5", "6", "7", "8")));
        finalList.add(new ArrayList<>(Arrays.asList("9", "10", "11", "12")));
        int checkCount1 = finalList.stream()
//                .map(l -> l.size())
                .map(List::size)
                .reduce(0, (res, n) -> res + n); // 後面可以加.intValue()
        System.out.println("checkCount1: " + checkCount1);
        int checkCount2 = finalList.stream()
//                .mapToInt(l -> l.size())
                .mapToInt(List::size)
                .sum();
        System.out.println("checkCount2: " + checkCount2);
    }
}
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章