天天看點

2021-11-15 Java8新特性 stream流分享

stream目錄

    • 1. stream 與 parallelStream
    • 2. filter
    • 3. findFirst() findAny()
    • 4. max min
    • 5. map flatMap
    • 6. reduce 規約(縮減) 實作集合求和,求乘積,求最值
    • 7. toList toMap toSet
    • 8. collect {count,averagingInt,averagingLong,averagingDouble,maxBy,minBy,summingInt,summingLong,summingDouble}
    • 9. groupingBy partitioningBy
    • 10. concat,distinct,iterate,skip,limit
    • 11. 讀取檔案流操作

1. stream 與 parallelStream

2. filter

3. findFirst() findAny()

4. max min

5. map flatMap

6. reduce 規約(縮減) 實作集合求和,求乘積,求最值

7. toList toMap toSet

8. collect {count,averagingInt,averagingLong,averagingDouble,maxBy,minBy,summingInt,summingLong,summingDouble}

9. groupingBy partitioningBy

10. concat,distinct,iterate,skip,limit

11. 讀取檔案流操作

直接上代碼

實體類

package net.work.util;

import lombok.Data;

@Data
public class Person {

    private String name;
    private String sex;
    private Integer age;
    private Integer money;

    public Person(String name,String sex, Integer age, Integer money) {
        this.name = name;
        this.age = age;
        this.money = money;
        this.sex = sex;

    }
}
    
           

測試

package net.work.util;

import java.io.File;
import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.Path;
import java.util.*;
import java.util.stream.Collectors;
import java.util.stream.Stream;

public class Commtest {
    static List<Person> personList = new ArrayList<>();

    private static void initPerson() {
        personList.add(new Person("張三", "男", 8, 3000));
        personList.add(new Person("李三", "男", 18, 5000));
        personList.add(new Person("孫六", "女", 18, 9000));
        personList.add(new Person("趙吧", "男", 19, 9000));
        personList.add(new Person("王五", "女", 26, 7000));
        personList.add(new Person("朱勇豪", "男", 24, 8000));
        personList.add(new Person("楊幂", "女", 26, 7000));
    }

    /**
     * 1.stream 與 parallelStream
     * 2.filter
     * 3.findFirst() findAny()
     * 4.max min
     * 5.map flatMap
     * 6.reduce   規約(縮減) 實作集合求和,求乘積,求最值
     * 7.toList toMap toSet
     * 8.collect  {count,averagingInt,averagingLong,averagingDouble,maxBy,minBy,summingInt,summingLong,summingDouble}
     * 9.groupingBy partitioningBy
     * 10.concat,distinct,iterate,skip,limit
     * 11.讀取檔案流操作
     *
     * @param args
     */
    public static void main(String[] args) {
        initPerson();
        personList.stream().filter(e -> e.getAge() > 18).forEach(System.out::println);

        System.out.println("_______________________________filter,findFirst________________________________");
        System.out.println(personList.stream().filter(e -> e.getAge() > 18).findFirst().stream().collect(Collectors.toList()));

        System.out.println("_______________________________parallelStream,findAny________________________________");
        System.out.println(personList.parallelStream().filter(e -> e.getAge() > 18).findAny().stream().collect(Collectors.toList()));

        System.out.println("________________________________filter,equals_______________________________");
        System.out.println(personList.stream().filter(e -> "張三".equals(e.getName())).collect(Collectors.toList()));

        System.out.println("________________________________max,comparing______________________________");
        System.out.println(personList.stream().max(Comparator.comparing(Person::getAge)).stream().collect(Collectors.toList()));

        System.out.println("_________________________________map______________________________");
        System.out.println(personList.stream().map(Person::getAge).collect(Collectors.toList()));

        System.out.println("__________________________________map,reduce_____________________________");
        // 求和
        System.out.println(personList.stream().map(Person::getAge).reduce(Integer::sum));
        // 求積
        System.out.println(personList.stream().map(Person::getAge).reduce((x, y) -> x * y));
        // 求最大
        System.out.println(personList.stream().map(Person::getAge).reduce((x, y) -> x > y ? x : y));

        System.out.println(personList.stream().map(Person::getMoney).reduce(Integer::sum));
        System.out.println(personList.stream().map(Person::getMoney).reduce(Integer::max));
        System.out.println(personList.stream().map(Person::getMoney).reduce(Integer::min));

        System.out.println("__________________________________filter,toMap_____________________________");
        Map<String, Person> collect = personList.stream().filter(e -> e.getAge() > 18).collect(Collectors.toMap(Person::getName, y -> y));
        System.out.println(collect);
        Set<Person> collect1 = personList.stream().filter(e -> e.getAge() > 18).collect(Collectors.toSet());
        System.out.println(collect1);


        System.out.println("__________________________________collect_____________________________");
        System.out.println(personList.stream().collect(Collectors.counting()));
        System.out.println(personList.stream().collect(Collectors.averagingInt(Person::getAge)));
        System.out.println(personList.stream().collect(Collectors.summingInt(Person::getMoney)));
        System.out.println(personList.stream().collect(Collectors.summarizingInt(Person::getMoney)));
        System.out.println(personList.stream().collect(Collectors.summarizingInt(Person::getAge)));
        System.out.println(personList.stream().collect(Collectors.maxBy(Comparator.comparing(Person::getAge))));


        System.out.println("_________________________________groupingBy,partitioningBy_____________________________");
        System.out.println(personList.stream().collect(Collectors.groupingBy(Person::getAge)));
        // 先按年齡分組,後按工資分組
        System.out.println(personList.stream().collect(Collectors.groupingBy(Person::getAge, Collectors.groupingBy(e -> e.getMoney() > 4000))));
        System.out.println(personList.stream().collect(Collectors.partitioningBy(e -> e.getAge() > 18)));

        System.out.println("_________________________________joining_____________________________");
        System.out.println(personList.stream().map(Person::getName).collect(Collectors.joining(",")));

        System.out.println("_________________________________sorted_____________________________");
        System.out.println(personList.stream().sorted(Comparator.comparing(Person::getMoney)).map(Person::getName).collect(Collectors.toList()));
        System.out.println(personList.stream().sorted(Comparator.comparing(Person::getMoney).reversed()).map(Person::getMoney).collect(Collectors.toList()));
        // 先按工資再按年齡自定義排序(降序)
        List<String> newList4 = personList.stream().sorted((p1, p2) -> {
            if (p1.getMoney().equals(p2.getMoney())) {
                return p2.getAge() - p1.getAge();
            } else {
                return p2.getMoney() - p1.getMoney();
            }
        }).map(Person::getName).collect(Collectors.toList());
        System.out.println("先按工資再按年齡自定義降序排序:" + newList4);


        System.out.println("_________________________________concat,distinct,iterate,skip,limit_____________________________");
        String[] arr1 = {"a", "b", "c", "d"};
        String[] arr2 = {"d", "e", "f", "g"};
        Stream<String> stream1 = Stream.of(arr1);
        Stream<String> stream2 = Stream.of(arr2);
        // concat:合并兩個流 distinct:去重
        List<String> newList = Stream.concat(stream1, stream2).distinct().collect(Collectors.toList());
        // limit:限制從流中獲得前n個資料
        List<Integer> collect2 = Stream.iterate(1, x -> x + 2).limit(10).collect(Collectors.toList());
        // skip:跳過前n個資料
        List<Integer> collect3 = Stream.iterate(1, x -> x + 2).skip(1).limit(5).collect(Collectors.toList());

        System.out.println("流合并:" + newList);
        System.out.println("limit:" + collect2);
        System.out.println("skip:" + collect3);


        System.out.println("_________________________________讀取檔案流操作_____________________________");
        String fileName = "C:\\Users\\24350\\Desktop\\B2幀解析.txt";
        Path path = new File(fileName).toPath();
        System.out.println(path);
        try (Stream<String> lines = Files.lines(path, StandardCharsets.UTF_8)) {
            lines.onClose(() -> System.out.println("Done!")).forEach(System.out::println);
        } catch (IOException e) {
            System.out.println("error{}" + e);
        }

    }


}
    
           

結果

Person(name=趙吧, sex=男, age=19, money=9000)
Person(name=王五, sex=女, age=26, money=7000)
Person(name=朱勇豪, sex=男, age=24, money=8000)
Person(name=楊幂, sex=女, age=26, money=7000)
_______________________________filter,findFirst________________________________
[Person(name=趙吧, sex=男, age=19, money=9000)]
_______________________________parallelStream,findAny________________________________
[Person(name=王五, sex=女, age=26, money=7000)]
________________________________filter,equals_______________________________
[Person(name=張三, sex=男, age=8, money=3000)]
________________________________max,comparing______________________________
[Person(name=王五, sex=女, age=26, money=7000)]
_________________________________map______________________________
[8, 18, 18, 19, 26, 24, 26]
__________________________________map,reduce_____________________________
Optional[139]
Optional[798999552]
Optional[26]
Optional[48000]
Optional[9000]
Optional[3000]
__________________________________filter,toMap_____________________________
{趙吧=Person(name=趙吧, sex=男, age=19, money=9000), 楊幂=Person(name=楊幂, sex=女, age=26, money=7000), 王五=Person(name=王五, sex=女, age=26, money=7000), 朱勇豪=Person(name=朱勇豪, sex=男, age=24, money=8000)}
[Person(name=趙吧, sex=男, age=19, money=9000), Person(name=王五, sex=女, age=26, money=7000), Person(name=朱勇豪, sex=男, age=24, money=8000), Person(name=楊幂, sex=女, age=26, money=7000)]
__________________________________collect_____________________________
7
19.857142857142858
48000
IntSummaryStatistics{count=7, sum=48000, min=3000, average=6857.142857, max=9000}
IntSummaryStatistics{count=7, sum=139, min=8, average=19.857143, max=26}
Optional[Person(name=王五, sex=女, age=26, money=7000)]
_________________________________groupingBy,partitioningBy_____________________________
{18=[Person(name=李三, sex=男, age=18, money=5000), Person(name=孫六, sex=女, age=18, money=9000)], 19=[Person(name=趙吧, sex=男, age=19, money=9000)], 24=[Person(name=朱勇豪, sex=男, age=24, money=8000)], 8=[Person(name=張三, sex=男, age=8, money=3000)], 26=[Person(name=王五, sex=女, age=26, money=7000), Person(name=楊幂, sex=女, age=26, money=7000)]}
{18={true=[Person(name=李三, sex=男, age=18, money=5000), Person(name=孫六, sex=女, age=18, money=9000)]}, 19={true=[Person(name=趙吧, sex=男, age=19, money=9000)]}, 24={true=[Person(name=朱勇豪, sex=男, age=24, money=8000)]}, 8={false=[Person(name=張三, sex=男, age=8, money=3000)]}, 26={true=[Person(name=王五, sex=女, age=26, money=7000), Person(name=楊幂, sex=女, age=26, money=7000)]}}
{false=[Person(name=張三, sex=男, age=8, money=3000), Person(name=李三, sex=男, age=18, money=5000), Person(name=孫六, sex=女, age=18, money=9000)], true=[Person(name=趙吧, sex=男, age=19, money=9000), Person(name=王五, sex=女, age=26, money=7000), Person(name=朱勇豪, sex=男, age=24, money=8000), Person(name=楊幂, sex=女, age=26, money=7000)]}
_________________________________joining_____________________________
張三,李三,孫六,趙吧,王五,朱勇豪,楊幂
_________________________________sorted_____________________________
[張三, 李三, 王五, 楊幂, 朱勇豪, 孫六, 趙吧]
[9000, 9000, 8000, 7000, 7000, 5000, 3000]
先按工資再按年齡自定義降序排序:[趙吧, 孫六, 朱勇豪, 王五, 楊幂, 李三, 張三]
_________________________________concat,distinct,iterate,skip,limit_____________________________
流合并:[a, b, c, d, e, f, g]
limit:[1, 3, 5, 7, 9, 11, 13, 15, 17, 19]
skip:[3, 5, 7, 9, 11]
_________________________________讀取檔案流操作_____________________________
C:\Users\24350\Desktop\B2幀解析.txt
68						幀标志1
01						幀長高位元組【L=10+length(DATA)】
39						幀長低位元組【從CTRLB開始到DATA止】
68						幀标志2
11						控制碼
00						0x00/0x80輔助控制碼,此處BIT7位若置位,則表示後續還有上線指令。

..............
Done!

Process finished with exit code 0