java-函数式接口与Stream流

函数式接口

有且仅有一个抽象方法的接口叫函数式接口。
@FunctionInterface注解可以检查该接口是否为函数式接口。

Myinterface in=() -> sout("函数式接口");

函数式接口作为方法的参数

startThread(Runnable r);

public class RunnableDemo {
    public static void main(String[] args) {
        startThread(()->{
            System.out.println(Thread.currentThread().getName());
        });
    }
    public static void startThread(Runnable r){
        new Thread(r).start();
    }
}

函数式接口作为返回值

public class ComparatorDemo {
    public static void main(String[] args) {
        ArrayList<String> array=new ArrayList<>();
        array.add("aa");
        array.add("bbb");
        array.add("cccc");
        array.add("d");
        Collections.sort(array,getComparator());
        System.out.println(array);
    }
    private static Comparator<String> getComparator(){
//        return new Comparator<String>() {
//            @Override
//            public int compare(String s1, String s2) {
//                return s1.length()-s2.length();
//            }
//        };
        return (s1,s2)->s1.length()-s2.length();
    }
}

Supplier

T get():获取结果
该方法不需要参数,他会按照某种实现逻辑(lambda表达式实现)返回一个数据。
生产型接口,如果指定了接口的泛型是什么数据,接口中的get方法就会生产什么类型的数据。

public class SupplierDemo {
    public static void main(String[] args) {
        String s = useSupplier(()->"hello");
        System.out.println(s);
    }
    private static String useSupplier(Supplier<String> sup){
        return sup.get();
    }
}

Consumer

消费型接口,不返回值。
void accept(T t);对给定的参数执行此操作
default Consumer andThen(Consumer after):返回一个组合的Consumer,依次执行此操作,然后执行after操作.

public class ConsumerDemo {
    public static void main(String[] args) {
        useConsumer("林青霞",s-> System.out.println(s));
    }
    private static void useConsumer(String s, Consumer<String> c){
        c.accept(s);
    }
}


--------------------------------
public class ConsumerDemo {
    public static void main(String[] args) {
        String[] str={"林青霞,30","刘艳,22","张曼玉,20","刘亦菲,23"};
        useConsumer(str,s ->{
            System.out.print("姓名:"+ s.split(",")[0]);
        },(s->{
            System.out.println(",年龄:"+s.split(",")[1]);
        }));
    }
    private static void useConsumer(String[] str, Consumer<String> c1,Consumer<String> c2){
        for (String s:str) {
            c1.andThen(c2).accept(s);
        }
    }
}

Predicate

boolean test(T t):对给定的参数进行判断,返回一个布尔值
default Predicate nagate():返回一个逻辑否
default Predicate and(Predicate other):返回一个组合判断,与
default Predicate or(Predicate other):返回一个组合判断,非

public class PredicateDemo {
    public static void main(String[] args) {
        System.out.println(checkString("hello",s->{
            return s.length()>9;
        }));
    }
    private static boolean checkString(String s,Predicate<String> p){
        return p.test(s);
               // return p.negate().test(s);
    }
}

-----------------------------------------------
public class PredicateDemo {
    public static void main(String[] args) {
        String[] str={"张曼玉,35","王祖贤,44","胡歌,35","刘亦菲,24","林青霞,30"};
        ArrayList<String> arrayList=uesPredicate(str,s->{
            return s.split(",")[0].length()>2;
        },s->{
            return Integer.parseInt(s.split(",")[1])>34;
        });
        System.out.println(arrayList);
    }
    private static ArrayList<String> uesPredicate(String[] str,Predicate<String> p1,Predicate<String> p2){
        ArrayList<String> arrayList=new ArrayList<>();
        for(String s:str){
            if(p1.and(p2).test(s))arrayList.add(s);
        }
        return arrayList;
    }
}

Function

Interface Function
接受一个T类型的参数,得到一个R类型的返回值。
R apply(T t):将此函数应用于给定的参数
default Function addThen(Function after):返回一个组合函数,首先将该函数应用于输入,然后将after函数应用于结果
Function<T,R>接口通常用于对参数进行处理,转换,然后返回新值

public class FunctionTest {
    public static void main(String[] args) {
        String str="林青霞,30";
        useFunction(str,s->{
            return Integer.parseInt(s.split(",")[1]);
        });
    }
    private static void useFunction(String s,Function<String,Integer> f1){
        System.out.println(f1.apply(s));
    }
}

----------------------------------------
public class FunctionTest {
    public static void main(String[] args) {
        String str="林青霞,30";
        useFunction(str,s->{
            return Integer.parseInt(s.split(",")[1]);
        },i->{
            return i+70;
        });
    }
    private static void useFunction(String s,Function<String,Integer> f1,Function<Integer,Integer> f2){
        System.out.println(f1.andThen(f2).apply(s));
    }
}

Stream流

将字符串进行多个判断时,单个写代码很繁琐,所以出现了Stream流。
生成流->中间操作->终结操作
Collection集合可以使用Stream()生成流:default Stream stream()
Map体系的集合间接生成流
数组可以通过of(T… values)生成流。

public class Streamliu {
    public static void main(String[] args) {
        ArrayList<String> arrayList=new ArrayList<>();
        arrayList.add("张曼玉");
        arrayList.add("张敏");
        arrayList.add("张全蛋");
        arrayList.add("刘亦菲");
//创建Stream流,filter传入Pridicate接口进行判断,forEach传入Consumer接口进行输出
        arrayList.stream().filter(s->s.startsWith("张")).filter(s->s.length()>2).forEach(System.out::println);
    }
}

list集合生成流

        //list集合生成流
        List<String> list=new ArrayList<String>();
        Stream<String> liststream=list.stream();

set集合生成流

        //set集合生成流
        Set<String> ss=new HashSet<String>();
        Stream<String> ssStream=ss.stream();

map生成流

   //map生成流
        Map<String,Integer> msi=new HashMap<String,Integer>();
        Stream<String> ssmsi=msi.keySet().stream();
        Stream<Integer> vmsi=msi.values().stream();
        Stream<Map.Entry<String,Integer>> entryStream=msi.entrySet().stream();

string生成流

//string生成流
        String[] str={"hello","world","java"};
        Stream<String> strStream=Stream.of(str);
        Stream<String> str1=Stream.of("hello","world");
        Stream<Integer> str2=Stream.of(10,20,30);

Stream流的操作方法

Stream filter(Predicate predicate):用于对流中的数据进行过滤

        ArrayList<String> arrayList=new ArrayList<>();
        arrayList.add("张曼玉");
        arrayList.add("张敏");
        arrayList.add("张全蛋");
        arrayList.add("刘亦菲");

        arrayList.stream().filter(s->{
            return s.startsWith("张");
        }).forEach(System.out::println);

Stream limit(long maxSize):返回此流中的元素组成的流,截取前指定参数个数的数据

        ArrayList<String> arrayList=new ArrayList<>();
        arrayList.add("张曼玉");
        arrayList.add("张敏");
        arrayList.add("张全蛋");
        arrayList.add("刘亦菲");

        arrayList.stream().limit(3).forEach(System.out::println);

Stream skip(long n);跳过指定参数个数的数据,返回由该流的剩余元素组成的流

        ArrayList<String> arrayList=new ArrayList<>();
        arrayList.add("张曼玉");
        arrayList.add("张敏");
        arrayList.add("张全蛋");
        arrayList.add("刘亦菲");

        arrayList.stream().skip(3).forEach(System.out::println);

Stream sorted();返回排序后的流
Stream sorted(Comparator comparator):根据排序器排序

     ArrayList<String> arrayList=new ArrayList<>();
        arrayList.add("张曼玉");
        arrayList.add("张敏");
        arrayList.add("张全蛋");
        arrayList.add("刘亦菲");

        arrayList.stream().sorted().forEach(System.out::println);
        arrayList.stream().sorted((s1,s2)->s1.length()-s2.length()).forEach(System.out::println);
        arrayList.stream().sorted((s1,s2)->{
            int num=s1.length()-s2.length();
            int num2=num==0?s1.compareTo(s2):num;
            return num2;
        }).forEach(System.out::println);

Stream map(Function mapper):返回由给定函数应用于此流的元素的结果组成的流

        ArrayList<String> arrayList=new ArrayList<>();
        arrayList.add("40");
        arrayList.add("20");
        arrayList.add("60");
        arrayList.add("10");
        arrayList.stream().map(s->Integer.parseInt(s)).forEach(System.out::println);

IntStream mapToInt(ToIntFunction mapper):返回一个IntStream其中包含将给定函数应用于此流的结果

        arrayList.stream().mapToInt(s->Integer.parseInt(s)).forEach(System.out::println);
        int result = arrayList.stream().mapToInt(Integer::parseInt).sum();
        System.out.println(result);

void foreach(Consumer action):对六种的每个元素执行操作
long count():返回此流中的元素数

        ArrayList<String> arrayList=new ArrayList<>();
        arrayList.add("40");
        arrayList.add("20");
        arrayList.add("60");
        arrayList.add("10");
        arrayList.stream().forEach(System.out::println);
        

例子

        ArrayList<String> arrayList1=new ArrayList<>();
        ArrayList<String> arrayList2=new ArrayList<>();
        arrayList1.add("胡歌");
        arrayList1.add("张张张");
        arrayList1.add("李纯钢");
        arrayList1.add("宋小宝");
        arrayList1.add("沙溢");
        arrayList1.add("马儿扎哈");
        arrayList2.add("迪丽热巴");
        arrayList2.add("古力娜扎");
        arrayList2.add("柳岩");
        arrayList2.add("林小小");
        arrayList2.add("王祖贤");
        arrayList2.add("林青霞");

        Stream<String> str1=arrayList1.stream().filter(s->s.length()==3).limit(3);
        Stream<String> str2=arrayList2.stream().filter(s->s.startsWith("林")).skip(1);
        Stream<String> concat = Stream.concat(str1, str2);

        concat.map(Actor::new).forEach(p->System.out.println(p.getName()));

Stream的收集操作

对数据使用Stream流的方式操作完毕后,收集到集合中
Stream流的收集方法
Rcollect(Collector collector):参数是一个Collector接口

工具类Collectors提供了具体的收集方式
public static Collector toList():把元素收集到List集合中
public static Collector toSet():把元素收集到Set集合中
public static Collector toMap(Function keyMapper,Function valueMapper):把元素收集到Map集合中

List集合

        List<String> List1=new ArrayList<>();
        List<String> List2=new ArrayList<>();
        List1.add("林青霞");
        List1.add("张曼玉");
        List1.add("刘艳");
        List1.add("王祖贤");
        Stream<String> str=List1.stream().filter(s->s.length()>2);
        List<String> collect = str.collect(Collectors.toList());
        for(String s:collect){
            System.out.println(s);
        }

set集合

        Set<String> collect = str.collect(Collectors.toSet());
        for(String s:collect){
            System.out.println(s);
        }

map集合

        String[] str={"周慧敏,20","张曼玉,25","林青霞,30","王祖贤,33"};
        Stream<String> strStream=Stream.of(str).filter(s->Integer.parseInt(s.split(",")[1])>29);
       Map<String,Integer> str1Stream=strStream.collect(Collectors.toMap((s->s.split(",")[0]), s->Integer.parseInt(s.split(",")[1])));
       Set<String> keyset=str1Stream.keySet();
       for(String s:keyset){
           int valule=str1Stream.get(s);
           System.out.println(s+","+valule);
       }
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值