Java8StreamApi

Java 8 中的 Stream 是对集合(Collection)对象功能的增强,它专注于对集合对象进行各种非常便利、高效的聚合操作(aggregate operation),或者大批量数据操作 (bulk data operation)。Stream API 借助于同样新出现的 Lambda 表达式,极大的提高编程效率和程序可读性。
(1)Stream自己不会储存元素
(2)Stream不会改变原对象。会返回一个持有结果的新的Stream
(3)Stream是延迟执行的,需要结果的时候才执行

1、Stream的创建

(1)通过Collection提供的Stream()或parallelStream()

List<String> list = new ArrayList<>();
list.stream()

(2)通过Arrays中的方法Stream()获取

String[] array = new String[2];
Arrays.stream(array);

(3)通过Stream的静态方法of()

Stream<String> stream = Stream.of("aaa","bbb","ccc");

2、Stream中间操作

Dog类

public class Dog {
    public int age;
    public String name;

    public Dog() {
    }

    public Dog(int age, String name) {
        this.age = age;
        this.name = name;
    }

    public int getAge() {
        return age;
    }

    public void setAge(int age) {
        this.age = age;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    @Override
    public boolean equals(Object o) {
        if (this == o) return true;
        if (o == null || getClass() != o.getClass()) return false;
        Dog dog = (Dog) o;
        return age == dog.age &&
                Objects.equals(name, dog.name);
    }

    @Override
    public int hashCode() {

        return Objects.hash(age, name);
    }

    @Override
    public String toString() {
        return "Dog{" +
                "age=" + age +
                ", name='" + name + '\'' +
                '}';
    }
}

创建一个List

List<Dog> list= Arrays.asList(
            new Dog(7, "DogA"),
            new Dog(6, "DogG"),
            new Dog(6, "DogC"),
            new Dog(46, "DogE"),
            new Dog(9, "DogW"),
            new Dog(9, "DogW")
);

(1)filter()筛选

//筛选出年龄大于6的
list.stream().filter(e -> e.age >6)

(2)limt()限制元素,使元素不超过指定数量

//限制2个
list.stream.limit(2)

(3)skip()跳过前n个元素,若不足n个返回一个空流

//跳过前两个
list.stream().skip(2)

(4)distinct()去重。注意需要重写hashCode和equals方法

list.stream().distinct()

(5)map()将元素映射成一个新的元素

list.stream().map(Dog::getName)

(6)sorted()自然排序(Comparable),sorted(Comparator com)定制排序

list.stream().sorted()
list.stream()
        .sorted((d1,d2)->{
             if(d1.getAge() == d2.getAge()){
                 return d1.getName().compareTo(d2.name);
             }
             else{
                 return Integer.compare(d1.age,d2.age);
             }
         })

3、终止操作

(1)allMatch() 检查是否匹配所有元素

Boolean type = list.stream().allMatch(e -> e.getAge() == 6);
//如果所有都等于6返回true,否则返回false

(2)anyMatch()至少匹配一个

Boolean type2 = list.stream().anyMatch(e -> e.getAge() == 6);
//只要有一个就返回true

(3)noneMatch()是否没有元素

Boolean type3 = list.stream().noneMatch(e -> e.getAge() == 6);
//全部不等于6返回true

(4)findFirst()返回第一个元素

list.stream().findFirst()

(5)findAny()返回任意一个元素

list.stream().findAny()

(6)count()返回元素总和

Long num = list.stream().count();

(7)max()返回最大值,min()返回最小值

list.stream().min(Comparator.comparing(Dog::getName));
list.stream().max(Comparator.comparingInt(Dog::getAge))

(8)reduce()将元素反复结合起来

List<Integer> numList = Arrays.asList(1,2,3,4,5,6,7,8,9);
Integer sum = numList.stream().reduce(0,(x,y)-> x + y);

Optional<Integer> sumAge = list.stream()
                .map(Dog::getAge)
                .reduce(Integer::sum);
System.out.println(sumAge.get());

(9)collect()收集

List<String> nameList = list.stream().map(Dog::getName)
                .collect(Collectors.toList());

Set<String> nameSet = list.stream().map(Dog::getName)
                .collect(Collectors.toSet());

HashSet<String> nameHashSet = list.stream().map(Dog::getName)
                .collect(Collectors.toCollection(HashSet::new));

分组

 Map<Integer, List<Dog>> groupList = list.stream().collect(Collectors.groupingBy(Dog::getAge));

Map<Boolean, List<Dog>> listMap = list.stream().collect(Collectors.partitioningBy(e -> e.age > 8));

DoubleSummaryStatistics any = list.stream().collect(Collectors.summarizingDouble(Dog::getAge));
System.out.println(any.getAverage());
System.out.println(any.getSum());

String name = list.stream()
                .map(Dog::getName)
                .collect(Collectors.joining(","));

test

public class StreamApi {

    List<Dog> list = Arrays.asList(
            new Dog(7, "DogA"),
            new Dog(6, "DogG"),
            new Dog(6, "DogC"),
            new Dog(46, "DogE"),
            new Dog(9, "DogW"),
            new Dog(9, "DogW")
    );

    @Test
    public void test1() {
        list.stream().filter(e -> e.age > 6)
                .limit(2)
                .forEach(System.out::println);
        System.out.println("-----------------------------------");
        list.stream()
                .distinct()
                .skip(2)
                .forEach(System.out::println);
    }

    @Test
    public void test2() {
        list.stream().map(Dog::getName)
                .sorted()
                .forEach(System.out::println);
        System.out.println("---------------");
        list.stream()
                .sorted((d1, d2) -> {
                    if (d1.getAge() == d2.getAge()) {
                        return d1.getName().compareTo(d2.name);
                    } else {
                        return Integer.compare(d1.age, d2.age);
                    }
                })
                .forEach(System.out::println);
    }

    @Test
    public void test3() {
        Boolean type = list.stream().allMatch(e -> e.getAge() == 6);
        System.out.println(type);
        System.out.println("------------------------------");

        Boolean type2 = list.stream().anyMatch(e -> e.getAge() == 6);
        System.out.println(type2);
        System.out.println("------------------------------");

        Boolean type3 = list.stream().noneMatch(e -> e.getAge() == 6);
        System.out.println(type3);
        System.out.println("------------------------------");
    }

    @Test
    public void test4() {
        Dog dog = list.stream().findFirst().get();
        System.out.println(dog);
        System.out.println("----------------------");

        Dog dog1 = list.stream().findAny().get();
        System.out.println(dog1);
        System.out.println("----------------------");

        Long num = list.stream().count();
        System.out.println(num);
        System.out.println("----------------");

        Dog dog2 = list.stream().max(Comparator.comparingInt(Dog::getAge)).get();
        System.out.println(dog2);
        System.out.println("------------------------");

        Dog dog3 = list.stream().min(Comparator.comparing(Dog::getName)).get();
        System.out.println(dog3);
        System.out.println("----------------------------");
    }

    @Test
    public void test5() {
        List<Integer> numList = Arrays.asList(1, 2, 3, 4, 5, 6, 7, 8, 9);
        Integer sum = numList.stream().reduce(0, (x, y) -> x + y);
        System.out.println(sum);
        System.out.println("-------------------------");

        Optional<Integer> sumAge = list.stream()
                .map(Dog::getAge)
                .reduce(Integer::sum);
        System.out.println(sumAge.get());
    }

    @Test
    public void test6() {
        List<String> nameList = list.stream().map(Dog::getName)
                .collect(Collectors.toList());
        System.out.println(nameList);
        System.out.println("------------------------");

        Set<String> nameSet = list.stream().map(Dog::getName)
                .collect(Collectors.toSet());
        System.out.println(nameSet);
        System.out.println("--------------------------");

        HashSet<String> nameHashSet = list.stream().map(Dog::getName)
                .collect(Collectors.toCollection(HashSet::new));
        System.out.println(nameHashSet);
        System.out.println("-----------------------------");

        //总数
        Long count = list.stream()
                .collect(Collectors.counting());

        //平均值
        Double avg = list.stream()
                .collect(Collectors.averagingDouble(Dog::getAge));
        System.out.println(avg);

        //年龄总和
        Double sumAge = list.stream()
                .collect(Collectors.summingDouble(Dog::getAge));
    }

    @Test
    public void test7(){
        Map<Integer, List<Dog>> groupMap = list.stream().collect(Collectors.groupingBy(Dog::getAge));
        System.out.println(groupMap);
        System.out.println(groupMap.get(6));
        System.out.println("--------------------");

        Map<Boolean, List<Dog>> listMap = list.stream().collect(Collectors.partitioningBy(e -> e.age > 8));
        System.out.println(listMap);
        System.out.println("------------------------");

        DoubleSummaryStatistics any = list.stream().collect(Collectors.summarizingDouble(Dog::getAge));
        System.out.println(any.getAverage());
        System.out.println(any.getSum());

        String name = list.stream()
                .map(Dog::getName)
                .collect(Collectors.joining(","));
        System.out.println(name);
    }

}

视频教程:
https://www.bilibili.com/video/av20812399/

猜你喜欢

转载自blog.csdn.net/superlover_/article/details/79150790