如何使用Java8 Stream()流處理集合

關注我,精彩文章第一時間推送給你

公眾號.jpg

簡介

Java 8 API添加了一個新的抽象稱為流Stream,可以讓你以一種聲明的方式處理數(shù)據。

Stream 使用一種類似用 SQL 語句從數(shù)據庫查詢數(shù)據的直觀方式來提供一種對 Java 集合運算和表達的高階抽象。

Stream API可以極大提高Java程序員的生產力,讓程序員寫出高效率、干凈、簡潔的代碼。

這種風格將要處理的元素集合看作一種流, 流在管道中傳輸, 并且可以在管道的節(jié)點上進行處理, 比如篩選, 排序,聚合等。

下面通過代碼了解下

創(chuàng)建學生類、精英學生類

/**
 * 定義學生類
 */
@Data
@AllArgsConstructor
class Student {
    private Integer id;
    private String name;
    private Integer age;
    private Double score;
}

/**
 * 定義精英學生類
 */
@Data
class EliteStudent {
    private String name;
    private Double score;
}

構建兩個集合,用于Stream()流處理

@Slf4j
@SpringBootTest
class StreamTest {

    private List<Student> list;
    private List<List<Student>> listFlat;

    @BeforeEach//注解在非靜態(tài)方法上
    void init() {
        list = Arrays.asList(
                new Student(1, "蓋倫1", 200, 66.0),
                new Student(2, "趙信", 21, 90.0),
                new Student(3, "樂芙蘭1", 21, 90.0),
                new Student(4, "李青", 50, 100d),
                new Student(5, "泰達米爾", 600, 90d)
        );

        listFlat = Arrays.asList(
                Arrays.asList(
                        new Student(1, "蓋倫1", 200, 66.0),
                        new Student(2, "趙信", 21, 90.0)
                ),
                Arrays.asList(
                        new Student(3, "樂芙蘭1", 21, 90.0),
                        new Student(4, "李青", 50, 100d)
                ),
                Collections.singletonList(
                        new Student(5, "泰達米爾", 600, 90d)
                )
        );
    }
    
    //各種流處理方法---------filter
    //----------------------map
    //--------------------reduce等等
        
}

1.filter

/**
     * filter
     * @DESC 過濾出list中學生名字中包括 "1" 的學生集合,
     *       并使用peek()利用其返回Stream<Student>直接以流的方式實現(xiàn)打印過濾出的學生
     *
     *       peek() 和 ForEach() 的區(qū)別:
     *       前者返回Stream<T> 可在流的基礎上繼續(xù)流操作
     *       后者返回void,想要繼續(xù)流操作需要進行二次流處理
     */
    @Test
    void filterTest() {
        final List<Student> collect = list.stream().filter(item -> item.getName().contains("1"))
                .peek(System.out::println)
                .collect(Collectors.toList());
        Assertions.assertEquals(2, collect.size());

        /**
         * 獲取過濾的第一條數(shù)據,如果包含則打印
         */
        list.stream().filter(item -> item.getName().contains("1"))
                .findFirst()
                .ifPresent(System.out::println);
    }

2.map

/**
     * map
     * @DESC 可以將List里面的對象轉化成新的對象
     * 1.將學生集合里不小于90分的作為精英學生過濾出來,并打印
     * 2.獲取所有學生的 name 集合,并打印
     */
    @Test
    void mapTest() {
        final List<EliteStudent> collect = list.stream().filter(item -> item.getScore() >= 90)
                .map(student -> {
                    EliteStudent eliteStudent = new EliteStudent();
                    BeanUtils.copyProperties(student, eliteStudent);
                    return eliteStudent;
                }).peek(System.out::println)
                .collect(Collectors.toList());
        Assertions.assertEquals(3, collect.size());

        final List<String> nameList = list.stream().map(Student::getName)
                .peek(System.out::println)
                .collect(Collectors.toList());
        Assertions.assertEquals(5, nameList.size());

    }

3.flatMap

/**
     * flatMap
     * @DESC 將嵌套列表轉換為普通列表,例如 List<List<Student>> 轉化為 List<Student>
     * 1.將嵌套列表轉化成普通列表,斷言轉化結果 = list
     * 2.轉化后獲取列表的 id 集合并打印
     * 3.轉化后再提取集合的分數(shù),求平均值,打印平均值
     */
    @Test
    void flatMapTest() {
        List<Student> collect = listFlat.stream().flatMap(Collection::stream)
                .peek(System.out::println)
                .collect(Collectors.toList());
        Assertions.assertEquals(collect, list);

        List<Integer> idList = listFlat.stream().flatMap(Collection::stream)
                .peek(System.out::println)
                .flatMapToInt(student -> IntStream.of(student.getId()))
                .peek(System.out::println)
                .boxed()
                .collect(Collectors.toList());
        Assertions.assertEquals(idList.size(), 5);

        listFlat.stream().flatMap(Collection::stream)
                .mapToDouble(Student::getScore)
                .average()
                .ifPresent(System.out::println);

    }

4.sorted

/**
     * sorted
     * @DESC 排序
     * 1.先按照分數(shù)倒敘排列,如果分數(shù)相同按照年齡正序排列,如果年齡相同按照 id 正序排列,打印
     * 2.如果 reversed() 寫在最后,則全部按照倒敘排列
     */
    @Test
    void sortedTest() {
        List<Student> collect = list.stream().sorted(Comparator.comparing(Student::getScore).reversed()
                .thenComparing(Student::getAge)
                .thenComparing(Student::getId))
                .peek(System.out::println)
                .collect(Collectors.toList());
        Assertions.assertEquals("李青", collect.get(0).getName());

        log.info("-------------------------------------------------------------");

        List<Student> collect2 = list.stream().sorted(Comparator.comparing(Student::getScore)
                .thenComparing(Student::getAge)
                .thenComparing(Student::getId).reversed())
                .peek(System.out::println)
                .collect(Collectors.toList());
        Assertions.assertEquals("李青", collect2.get(0).getName());
    }

5.match

/**
     * match
     * @DESC 驗證list中的每一項是否匹配我們的條件
     * allMatch 全都匹配
     * anyMatch 任意匹配
     * noneMatch 全不匹配
     *
     * 設置匹配條件為正則表達式 ^[1-9]\\d*$ 正整數(shù)
     * 1.驗證list的id是否全都匹配條件
     * 2.臨時改變list的第一個年齡為 -1 驗證是否年齡任意一個匹配條件
     * 3.驗證分數(shù)是否全不匹配條件
     */
    @Test
    void matchTest() {
        boolean b = list.stream().allMatch(item -> ReUtil.isMatch("^[1-9]\\d*$", item.getId().toString()));
        log.info("輸出list的id是否全部匹配條件,結果:----------[{}]", b);

        list.get(0).setAge(-1);
        list.forEach(System.out::println);
        boolean b1 = list.stream().anyMatch(item -> ReUtil.isMatch("^[1-9]\\d*$", item.getAge().toString()));
        log.info("輸出list的年齡是否任意匹配條件,結果:----------[{}]", b1);

        boolean b2 = list.stream().noneMatch(item -> ReUtil.isMatch("^[1-9]\\d*$", item.getScore().toString()));
        log.info("輸出list的年齡是否都不匹配條件,結果:----------[{}]", b2);

    }

6.reduce

/**
     * reduce
     * @DESC 合并流元素產生單個值
     * 1.計算list中所有學生年齡的總和,存在則打印
     * 2.計算list中所有學生年齡的總和,存在則打印
     */
    @Test
    void reduceTest() {
        list.stream().map(Student::getAge)
                .reduce(Integer::sum)
                .ifPresent(System.out::println);

        list.stream().map(Student::getScore)
                .reduce(Double::sum)
                .ifPresent(System.out::println);
    }

7.collertor

/**
     * collector
     * 收集器,主要用于toList() / toSet() / toMap() / joining()連接字符串
     * 1.把list中的id作為key, name作為value轉化成Map
     * 2.把學生名字用逗號拼接,并且第一個逗號用星號替換
     */
    @Test
    void collectorTest() {

        Map<Integer, String> map = list.stream().collect(Collectors.toMap(Student::getId, Student::getName));
        map.forEach((k, v) -> log.info("key = {} , value = {}", k, v));

        String s = list.stream().map(Student::getName)
                .collect(Collectors.joining(","))
                .replaceFirst(",", "*");
        log.info("輸出逗號拼接的字符串-->{}", s);

    }

8.summarizingDouble

/**
     * summarizingDouble
     * 1.計算集合中某個元素的 count / sum / avg / min / max
     * 2.第二種寫法
     */
    @Test
    void summarizingDoubleTest() {
        DoubleSummaryStatistics collect = list.stream()
                .collect(Collectors.summarizingDouble(Student::getScore));
        System.out.println(collect);

        DoubleSummaryStatistics doubleSummaryStatistics = list.stream()
                .mapToDouble(Student::getScore)
                .summaryStatistics();
        System.out.println(doubleSummaryStatistics);
    }

9.partitioningBy

/**
     * partitioningBy
     * @DESC 用于分割列表
     * 把學生列表中年齡大于100的放進key為true的Map中
     * 小于等于100的放進key為false的Map中
     */
    @Test
    void partitioningByTest() {
        Map<Boolean, List<Student>> map = list.stream()
                .collect(Collectors.partitioningBy(e -> e.getAge() > 100));
        log.info("true列表 = {}", map.get(Boolean.TRUE));
        log.info("false列表 = {}", map.get(Boolean.FALSE));
    }

10.groupingBy

/**
     * groupingBy
     * @DESC 分組
     * 1.根據成績分組
     * 2.獲取每個分數(shù)的人數(shù)
     * 3.根據成績獲取取得每個成績的學生的總分
     */
    @Test
    void groupingByTest() {
        Map<Double, List<Student>> map1 = list.stream().collect(Collectors.groupingBy(Student::getScore));
        map1.forEach((k, v) -> System.out.println(k + "\t" + v));

        Map<Double, Long> map2 = list.stream().collect(Collectors.groupingBy(Student::getScore, Collectors.counting()));
        map2.forEach((k,v) -> System.out.println(k + "\t" + v));

        Map<Double, Double> map3 = list.stream()
                .collect(Collectors.groupingBy(Student::getScore, Collectors.summingDouble(Student::getScore)));
        map3.forEach((k, v) -> System.out.println(k + "\t" + v));
    }

11.parallel

/**
     * parallel
     * @DESC 并發(fā)
     * 延遲一秒后,并發(fā)的打印出學生的名字
     */
    @Test
    void parallel() {
        list.stream().parallel().forEach(this::print);
    }

    private void print(Student student) {
        try {
            TimeUnit.SECONDS.sleep(1);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        log.info("學生的名字是 : {}", student.getName());
    }

12.讀寫文件

/**
     * @DESC 讀寫文件
     * 先把list中的數(shù)據寫到student.txt中
     * 再讀取出來
     */
    @Test
    void fileTest() throws IOException {
        PrintWriter printWriter = new PrintWriter(Files.newBufferedWriter(Paths.get("D://student.txt")));
        //list列表寫出到文件student.txt中
        list.forEach(printWriter::println);
        printWriter.close();
        //讀取文件
        List<String> collect = Files.lines(Paths.get("D://student.txt"))
                .peek(System.out::println)
                .collect(Collectors.toList());
        Assertions.assertEquals(5, collect.size());
    }
?著作權歸作者所有,轉載或內容合作請聯(lián)系作者
【社區(qū)內容提示】社區(qū)部分內容疑似由AI輔助生成,瀏覽時請結合常識與多方信息審慎甄別。
平臺聲明:文章內容(如有圖片或視頻亦包括在內)由作者上傳并發(fā)布,文章內容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務。

相關閱讀更多精彩內容

友情鏈接更多精彩內容