函数式接口和stream流

一.函数式接口

函数式接口:有且仅有一个抽象方法的接口。Java的函数式接口编程提现的就是Lambda表达式,所以函数式接口就是适用于Lambda表达式的接口。

1.快速入门

        @FunctionalInterface//标志着这个接口是一个函数式接口。如果在该注解修饰下的接口中声明了两个及以上的方法,那么就会报错。我们自己在定义函数式接口时,这个注解是可以不加的,只要符合函数式接口的定义,就是函数式接口,但是建议加上。
//函数式接口
@FunctionalInterface//标志着这个接口是一个函数式接口
package com.guguo.test.stream;
public interface FunctionInterface {
    void hello();
}

//测试
package com.guguo.test.stream;
public class Test {
    public static void main(String[] args) {
        FunctionInterface functionInterface=()->{
            System.out.println("hello,world");
        };
        functionInterface.hello();
    }
}

2.函数式接口使用

作为方法的参数

//函数式接口
package com.guguo.test.lambda;
@FunctionalInterface
public interface Eatable {
    void eat();
}

//测试
package com.guguo.test.lambda;
public class EatableDemo  {
    public static void main(String[] args) {
        EatableDemo.useEatable(()->{
            System.out.println("吃饱饱,睡觉觉");
        });
    }
    public static void useEatable(Eatable e){
        e.eat();
    }
}

作为返回值

//函数式接口
package com.guguo.test.stream;
@FunctionalInterface
public interface ComparatorInterface {
    void compare();
}

//测试
package com.guguo.test.stream;
public class Test2 {
    public static void main(String[] args) {
        ComparatorInterface comparatorInterface = getComparatorInterface();
        comparatorInterface.compare();
    }
    //这个方法返回了一个函数式接口
    public static ComparatorInterface getComparatorInterface() {
        return ()->{
            System.out.println("函数式接口进行比较");
        };
    }
}

3.常见函数式接口

Supplier<T>接口

T get() :获得结果。该方法不需要参数,他会依照某种实现逻辑(由Lambda表达式实现)返回一个数据。这个接口也被称为生产型接口,我们指定类型是什么,他就产生什么样的数据供我们使用。

package com.guguo.test.stream;
import java.util.function.Supplier;
public class SupplierDemo {
    public static void main(String[] args) {
        Supplier<String> supplier=()->"我是返回的字符串";//此时定义的是字符串类型
        String s = supplier.get();
        System.out.println(s);
    }
}

Consumer接口

包含两个方法,

void accept<T> 对给定的参数执行此操作
default Consumer<T> andThen(Consumer after):返回一个组合的Consumer,依次执行此操作,然后执行after操作。

该接口被称之为消费型接口,他消费的数据的数据类型由泛型指定。

package com.guguo.test.stream;
import java.util.function.Consumer;

public class ConsummerDemo {
    public static void main(String[] args) {
        ConsumerTest("小王子的玫瑰花",s-> System.out.println(s));//一次简单的消费操作

        Consumer<String> consumer=s-> System.out.println(s+"园");//多次连续的消费
        Consumer<String> consumer1 = consumer.andThen(s -> System.out.println(s+"园们"));
        ConsumerTest("小王子的玫瑰花",consumer1);
    }
    public static void ConsumerTest(String s, Consumer<String> consumer) {
        consumer.accept(s);
    }
}

Predict<T>接口

常见的有四个方法:
boolean test(T t):对给定的参数进行判断,返回一个布尔值
default Predicate<T> negate(): 返回一个逻辑的否定,对应逻辑非
default Predicate<T> add(Predicate other): 返回一个组合判断,对应短路与
default Predicate<T> or(Predicate other): 返回一个组合判断,对应短路或

package com.guguo.test.stream;

import java.util.function.Predicate;

public class PredictDemo {
    public static void main(String[] args) {
        Predicate<Integer> predicate=x-> x>10;//判断给定的数字是否满足要求
        boolean test = predicate.test(3);
        System.out.println(test);
        boolean test1 = predicate.negate().test(3);//对得到的结果进行否定
        System.out.println(test1);
        Predicate<Integer> predicate2=x-> x>1;
        boolean test2 = predicate.and(predicate2).test(3);//使用不同的判断,然后将两个判断的结果进行与操作
        System.out.println(test2);
        boolean test3 = predicate.or(predicate2).test(3);//使用不同的判断,然后将两个判断的结果进行或操作
        System.out.println(test3);
    }
}

Function<T,R>接口

T是函数输入的类型,R是函数结果的类型。表示接受一个参数并产生结果的函数

R apply<T t>:将此函数应用与给定的参数。
default  <V>     FunctionandThen<Function <> extends R> ,? extends after>  :返回一个组合函数,首先将函数应用于其输入,然后将after函数应用于结果。

package com.guguo.test.stream;
import java.util.function.Function;

public class FunctionDemo {
    public static void main(String[] args) {
        //基本用法1
        Function<String,Integer> function=s->Integer.valueOf(s);//将字符串转变成数字
        Integer apply = function.apply("123");
        System.out.println(apply);
        //基本用法2
        Function<Integer,String> function2=x->x.toString();//将数字转变成字符串
        String apply1 = function2.apply(423);
        System.out.println(apply1);

        //高端操作
        //把一个字符串转变成整数,然后把整数加1,再转变成字符串
        Function<String,Integer> function3=s->{
            Integer x = Integer.valueOf(s);
            x++;
            return x;
        };
        Function<Integer,String> function4=x->x.toString();
        String apply2 = function3.andThen(function4).apply("456");
        System.out.println(apply2);
    }
}

二.Stream流

1.stream流的生成方式

1.首先是使用数据源生成流 list.stream();
        1.Connection体系的集合可以使用默认方法stream()生成流;
        2.Map体系的集合间接的生成流;
        3.数组可以通过Stream接口的静态方法of(T values)生成流
2.中间流操作,一个流后面可以跟很多中间操作,主要是打开流做出某种程度的数据过滤和映射,然后返回一个新的流
3.终结操作。一个流只能有一个终结流操作。比如forEach();

package com.guguo.test.stream;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.Map;
import java.util.stream.Stream;

public class createStream {
    public static void main(String[] args) {
        //1.Connection体系的集合可以使用默认方法stream()生成流;
        ArrayList<String> list = new ArrayList<>();
        Stream<String> stream = list.stream();
        //2.Map体系的集合间接的生成流;
        HashMap<String, String> map = new HashMap<>();
        Stream<String> stream1 = map.keySet().stream();
        Stream<String> stream2 = map.values().stream();
        Stream<Map.Entry<String, String>> stream3 = map.entrySet().stream();
        //3.数组可以通过Stream接口的静态方法of(T values)生成流
        Stream<Integer> numbers1 = Stream.of(3,4,5,6,7,84,4);
    }
}

2.中间操作filter

Stream<T>  filter(Predicate predicate) :用于对流中的数据进行过滤。满足条件的留下来,不满足条件的过滤掉。

package com.guguo.test.stream;

import java.util.stream.Stream;

public class filterDemo {
    public static void main(String[] args) {
        Stream<Integer> numbers = Stream.of(3,4,5,6,7,84,4);
        Stream<Integer> integerStream = numbers.filter(x -> x > 10);
        integerStream.forEach(s-> System.out.println(s));//此时只留下了84
    }
}

3.中间操作limit和skip

Stream<T>  limit(long maxSize):返回此流中的元素组成的流,截取前指定参数个数的数据
Steam<T> skip(long n): 跳过指定个数的数据,返回由该流的剩余元素组成的流

package com.guguo.test.stream;
import java.util.stream.Stream;

public class limitDemo {
    public static void main(String[] args) {
        Stream<Integer> numbers = Stream.of(3,4,5,6,7,84,4);
        Stream<Integer> integerStream = numbers.limit(4);
        integerStream.forEach(s-> System.out.println(s));//3,4,5,6
    }
}
package com.guguo.test.stream;
import java.util.stream.Stream;

public class skipDemo {
    public static void main(String[] args) {
        Stream<Integer> numbers = Stream.of(3,4,5,6,7,84,4);
        Stream<Integer> integerStream = numbers.skip(3);
        integerStream.forEach(s-> System.out.println(s));//6,7,84,4
    }
}

4.中间操作concat和第distinct

static   Stream<T>  concat(Stream a,String b);合并ab两个流为一个流
Stream<T>  distinct();返回由该流的不同元素组成的流,就是去掉流中的重复元素。

package com.guguo.test.stream;
import java.util.stream.Stream;

public class concatDemo {
    public static void main(String[] args) {
        Stream<Integer> numbers1 = Stream.of(3,4,5,6,7,84);
        Stream<Integer> numbers2 = Stream.of(7,84,4);
        Stream<Integer> concat = Stream.concat(numbers1, numbers2);
        concat.forEach(s-> System.out.println(s));//3,4,5,6,7,7,84,84,4
    }
}
package com.guguo.test.stream;
import java.util.stream.Stream;

public class distinctDemo {
    public static void main(String[] args) {
        Stream<Integer> numbers = Stream.of(3,4,5,6,7,84,7,84,4);
        Stream<Integer> distinct = numbers.distinct();
        distinct.forEach(s-> System.out.println(s));//3,4,5,6,7,84,4
    }
}

5.中间操作sorted

Stream<T>  sorted(); 返回由此流元素组成的流,根据自然顺序排序
Stream<T>  sorted(Comparator comparator); 返回由此流元素组成的流,根据提供比较器进行排序

package com.guguo.test.stream;
import java.util.stream.Stream;

public class sortedDemo {
    public static void main(String[] args) {
        Stream<Integer> numbers1 = Stream.of(3,4,5,6,7,84,7,84,4);
        numbers1.sorted().forEach(s-> System.out.println(s));//从小到大排序
        Stream<Integer> numbers2 = Stream.of(3,4,5,6,7,84,7,84,4);
        numbers2.sorted((x,y)->{return y-x;}).forEach(s-> System.out.println(s));//从大到小排序
    }
}

6.中间操作map,mapToInt

Stream<R>  map(Function map):返回由给定函数应用于此流的元素的结果组成的流。
IntStream mapToInt(Function map):返回一个IntStream其中包含将给定函数应用于此流的结果

package com.guguo.test.stream;
import java.util.stream.Stream;

public class mapDemo {
    public static void main(String[] args) {
        Stream<String> stringStream = Stream.of("10","20","30","40","50","60");//将这个字符串流转变成Integer流,并且都+1
        Stream<Integer> integerStream = stringStream.map(s -> {
            Integer x = Integer.valueOf(s);
            return ++x;
        });
        integerStream.forEach(x-> System.out.println(x));
    }
}
package com.guguo.test.stream;
import java.util.stream.Stream;

public class mapToIntDemo {
    public static void main(String[] args) {
        Stream<String> stringStream = Stream.of("10","20","30","40","50","60");//将这个字符串流转变成Integer流
        stringStream.mapToInt(Integer::parseInt).forEach(s-> System.out.println(s));
    }
}

7.终结操作forEach和count

package com.guguo.test.stream;
import java.util.stream.Stream;

public class forEachDemo {
    public static void main(String[] args) {
        Stream<String> stringStream = Stream.of("10","20","30","40","50","60");
        stringStream.forEach(s-> System.out.println(s));//里面的函数式接口是Consumer
    }
}
package com.guguo.test.stream;
import java.util.stream.Stream;

public class countDemo {
    public static void main(String[] args) {
        Stream<String> stringStream = Stream.of("10","20","30","40","50","60");
        System.out.println(stringStream.count());
    }
}

8.收集操作

package com.guguo.test.stream;
import java.util.Map;
import java.util.stream.Collectors;
import java.util.stream.Stream;

public class collectDemo {
    public static void main(String[] args) {
        Stream<String> stringStream = Stream.of("张三,10","王五,20","赵六,30");
        //把上面的值转变成map形式。
        Map<String, String> collect = stringStream.collect(Collectors.toMap(
                s -> s.split(",")[0],
                s -> s.split(",")[1]
        ));
        System.out.println(collect);
    }
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值