java流式編程

Reference

Lambda之Stream流式編程;
20道關(guān)于Stream流的題目練習(xí);

\color{red}{注意:所有的流對象只能使用一次,重復(fù)使用會報錯:}
\color{red}{Exception in thread "main" java.lang.IllegalStateException: stream has already been operated upon or closed}
題目1:篩選學(xué)生不及格次數(shù)2次及2次以上的學(xué)生列表

        List<String> failCountStudent = studentList.stream().filter(s -> s.getFailCount()>=2).map(s -> s.getName()).collect(Collectors.toList());
        System.out.println(failCountStudent);

題目:2:篩選班主任和科任老師負(fù)責(zé)的學(xué)生中有多少個不及格次數(shù)超過2次的

        Map<String, List<Student>> arrayList1 = studentList.stream().filter(s -> s.getFailCount() >= 1).collect(Collectors.groupingBy(Student::getChineseTeacher));
        System.out.println(arrayList1.size());
        //遍歷
        for(Map.Entry<String, List<Student>> entry:arrayList1.entrySet()){
            System.out.println(entry.getKey()+"--->"+entry.getValue());
        }

題目3:篩選不及格次數(shù)超過2次且班主任不是王老師和汪老師的

        List<Student>  students =  studentList.stream().filter(s -> s.getFailCount() >= 2 && (!"王老師".equals(s.getChineseTeacher()) && !"汪老師".equals(s.getChineseTeacher()))).collect(Collectors.toList());
        System.out.println(students);

題目4:提取學(xué)生列表中所有學(xué)生的名字

        List<String>  nameList = studentList.stream().map(s -> s.getName()).collect(Collectors.toList());
        System.out.println(nameList);

題目5:提取不及格次數(shù)為0的學(xué)生為三好學(xué)生并給isMeritStudent 賦值

        List<Student> meritStudents = studentList.stream().map(s -> {
        if (s.getFailCount() == 0){
            s.setIsMeritStudent(true);
        } else {
            s.setIsMeritStudent(false);
        }
        return s;
        }).collect(Collectors.toList());
        System.out.println(meritStudents);

題目6:統(tǒng)計所有老師名字,并列出所有老師所帶的學(xué)生

        System.out.print("----------------------------------------------This is ChineseTeacher:\n");
        Map<String,List<Student>> chineseTeacherMap =  studentList.stream().collect(Collectors.groupingBy(Student::getChineseTeacher));
        for(Map.Entry<String, List<Student>> entry:chineseTeacherMap.entrySet()){
            System.out.println(entry.getKey()+"--->"+entry.getValue());
        }
        System.out.println("----------------------------------------------This is ClassTeacher:\n");
        Map<String, List<Student>> classTeacherMap = studentList.stream().collect(Collectors.groupingBy(Student::getClassTeacher));
        for(Map.Entry<String, List<Student>> entry:classTeacherMap.entrySet()){
            System.out.println(entry.getKey()+"--->"+entry.getValue());
        }

題目7:有如下整數(shù)1,-1,-2,-3,-4,-5 使用Stream取元素絕對值并打印

        Stream<Integer> stream = Stream.of(1, -1,-2, -3,-4, -5);
        stream.map(Math::abs).forEach(System.out::println);

題目8:給定一個數(shù)字列表,如何返回一個由每個數(shù)的平方構(gòu)成的列表

        List<Integer> list = Arrays.asList(1,2,3,4,6,5);
        list.stream().map(x -> x * x).forEach(System.out::println);

如下有7個元素黃藥師,馮蘅,郭靖,黃蓉,郭蓉 ,郭襄,郭破虜
題目9:使用stream將以郭字開頭的元素存入新集合

        Stream<String> stream = Stream.of("黃藥師", "郭靖", "黃蓉", "宋江", "郭霞", "郭美");
        List<String> list = stream.collect(Collectors.toList()).stream().filter(s -> s.startsWith("郭")).collect(Collectors.toList());
        System.out.println(list);

已知ArrayList集合中有如下元素{陳玄風(fēng)、梅超風(fēng)、陸乘風(fēng)、曲靈風(fēng)、武眠風(fēng)、馮默風(fēng)、羅玉風(fēng)}
題目10:取出前兩個元素并在控制臺打印輸出
題目11:取出后兩個元素并在控制臺打印輸出

        List str = new ArrayList<>();
        str.add("陳玄風(fēng)");
        str.add("梅超風(fēng)");
        str.add("陸乘風(fēng)");
        str.add("曲靈風(fēng)");
        str.add("武眠風(fēng)");
        str.add("馮默風(fēng)");
        str.add("羅玉風(fēng)");
        Stream<String> stream = str.stream();
        stream.limit(2).forEach(System.out::println);
        //stream.limit(2).forEach(e -> System.out.println(e));
        System.out.println("-----------------------");
        Stream<String> stream1 = str.stream();
        stream1.skip(str.size() - 2).forEach(System.out::println);

題目12:找出2011年發(fā)生的所有交易, 并按交易額排序(從低到高)

        
        List<Transaction> transcations = Arrays.asList(
                new Transaction(2011,300),
                new Transaction(2012,1000),
                new Transaction(2011,400),
                new Transaction(2012,800),
                new Transaction(2011,350)

        );
        Stream<Transaction> stream = transcations.stream();
        List<Transaction> list = stream.filter(s -> s.getYear() == 2011).sorted((e1, e2) -> e1.getValue() - e2.getValue()).collect(Collectors.toList());
        System.out.println(list);

題目13:怎樣使用map和reduce方法數(shù)一數(shù)流中有多少個Transaction呢?

        Stream<Transaction> stream1 = transcations.stream();
        Integer sum = stream1.map(e -> 1).reduce(Integer::sum).get();
        System.out.println(sum);

題目14:現(xiàn)在有兩個Arraylist集合,分別存儲6名男演員和6女演員的名稱,要求完成如下的操作:
題目15:把過濾后的男演員女演員合并

        List<Actor> womanList = Arrays.asList(
                new Actor("林美麗", false),
                new Actor("阿花", false),
                new Actor("林黛玉", false),
                new Actor("韓紅", false),
                new Actor("林沖", false),
                new Actor("李麗", false)
        );
        List<Actor> manList = Arrays.asList(
                new Actor("趙聰", true),
                new Actor("錢精忠", true),
                new Actor("孫飛", true),
                new Actor("李光", true),
                new Actor("周斌", true),
                new Actor("吳正", true)
        );
        List<Actor> womanResults = womanList.stream().filter(e -> e.getName().startsWith("林")).skip(1).collect(Collectors.toList());
        System.out.println(womanResults);
        
        List<Actor> unionActors = Stream.concat(womanResults.stream(),manList.stream()).collect(Collectors.toList());
        System.out.println(unionActors);

我國有34個省級行政區(qū),分別是:
23個省:河北省、山西省、吉林省、遼寧省、黑龍江省、陜西省、甘肅省、青海省、山東省、福建省、浙江省、臺灣省、河南省、湖北省、湖南省、江西省、江蘇省、安徽省、廣東省、海南省、四川省、貴州省、云南省。
4個直轄市:北京市、天津市、上海市、重慶市。 5個自治區(qū):內(nèi)蒙古自治區(qū)、新疆維吾爾自治區(qū)、寧夏回族自治區(qū)、廣西壯族自治區(qū)、西藏自治區(qū)。
2個特別行政區(qū):香港特別行政區(qū)、澳門特別行政區(qū)。 請使用流依次完成下列操作:
題目17:統(tǒng)計不是三個字的省份的個數(shù)
題目18:統(tǒng)計名字中包含方位名詞的省份(東西南北)的個數(shù)
題目19:打印名字中包含方位名詞的普通省份(非自治區(qū)直轄市特別行政區(qū))的名字
題目20:將所有的特殊省份(自治區(qū)直轄市特別行政區(qū))提取出來并放到新數(shù)組中

        List<String> provinces = Arrays.asList("河北省", "山西省", "吉林省", "遼寧省",
                "黑龍江省", "陜西省", "甘肅省", "青海省", "山東省",
                "福建省", "浙江省", "臺灣省", "河南省", "湖北省",
                "湖南省", "江西省", "江蘇省", "安徽省", "廣東省",
                "海南省", "四川省", "貴州省", "云南省", "北京市",
                "天津市", "上海市", "重慶市", "內(nèi)蒙古自治區(qū)",
                "新疆維吾爾自治區(qū)", "寧夏回族自治區(qū)", "廣西壯族自治區(qū)",
                "西藏自治區(qū)", "香港特別行政區(qū)", "澳門特別行政區(qū)");
        Long sum = provinces.stream().filter(s -> s.length() != 3).count();
        System.out.println(sum);
        Long sum = provinces.stream().filter(s -> s.contains("東")||s.contains("西")||s.contains("南")||s.contains("北")).count();
        System.out.println(sum);
        provinces.stream().filter(s -> !s.contains("自治區(qū)") && !s.contains("直轄市") && !s.contains("特別行政區(qū)") && (s.contains("東")||s.contains("西")||s.contains("南")||s.contains("北"))).forEach(e -> System.out.println(e));

       List<String> exceptProvinces  = provinces.stream().filter(s -> s.contains("自治區(qū)")|| s.contains("直轄市") || s.contains("特別行政區(qū)") ).collect(Collectors.toList());
       System.out.println(exceptProvinces);

題目21:判斷對象某一屬性值是否相同

        List<EnquiryOrder> enquiryOrders = commonDao.loadAll(EnquiryOrder.class, ids);
        String firstCompanyName = enquiryOrders.get(0).getCompanyName();
        //所有公司名都相同,返回true,否則返回false
        Boolean isSameCompany = enquiryOrders.stream().map(EnquiryOrder::getCompanyName).allMatch(firstCompanyName :: equals);
最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

  • 知識點(diǎn): 線程生命周期(新建、運(yùn)行、阻塞、等待(一直等待)、超時等待(超時取消等待)、終止); Synchroni...
    CJ21閱讀 1,840評論 1 21
  • Java異步編程實(shí)戰(zhàn) chap1 認(rèn)識異步編程 異步編程概念與作用在使用同步編程方式時,由于每個線程同時只能發(fā)起一...
    landon30閱讀 1,296評論 0 0
  • 一、基礎(chǔ)篇JVM JVM內(nèi)存結(jié)構(gòu) 堆、棧、方法區(qū)、直接內(nèi)存、堆和棧區(qū)別 https://blog.csdn.net...
    jackcooper閱讀 1,441評論 2 61
  • 《 Kotlin + Spring Boot : 下一代 Java 服務(wù)端開發(fā) 》 《Spring Boot 開發(fā)...
    光劍書架上的書閱讀 9,560評論 32 123
  • 集合優(yōu)化了對象的存儲,而流則是對數(shù)據(jù)的處理 流是一系列與特定存儲機(jī)制無關(guān)的元素,利用流,我們無需迭代集合中的元素,...
    Jay丶x閱讀 1,060評論 0 0

友情鏈接更多精彩內(nèi)容