方法引用之其他使用

package com.Lucky.Function;

import java.util.ArrayList;
import java.util.Collections;
import java.util.Locale;
import java.util.function.Function;
import java.util.function.IntFunction;

/*
  使用类名引用成员方法       Integer::parseInt
  使用数组的构造方法         Integer[]::new
 */
//要求:将集合的字符串字母大写再输出
public class otherFunction {

    public static void main(String[] args) {
        String str="wdfgnbvcwsdfgh";
        ArrayList<String> list=new ArrayList<>();
        Collections.addAll(list,"sdwe","dfger","wertygh");

        System.out.println("--匿名内部类写法----");
        list.stream().map(new Function<String, String>() {
            @Override
            public String apply(String s) {
                String s1 = s.toUpperCase();
                return s1;
            }
        }).forEach(s -> System.out.println(s));

        System.out.println("--lamda写法----");
        list.stream().map( s->s.toUpperCase()).forEach(s -> System.out.println(s));


        System.out.println("--①类名引用成员方法:要根据独有的条件使用----");
        /*
          public String toUpperCase() {
             return toUpperCase(Locale.getDefault());
          }
          疑问点:上面String类的toUpperCase源码,可是为什么明跟抽象方法的形参不一样还可以使用方法引用呢?????

           方法引用:
         使用条件:1.引用地方要是函数式接口:@FunctionalInterface
                 2.被引用的方法必须存在
                 3.被引用的方法的形参以及返回值要跟抽象方法的保持一致【区别在这】
                 {****
                   被引用的方法的形参,需要跟抽象方法的第二个形参开始要保持一致,
                   如果抽象方法中没有第二个形参,那么被引用方法需要的是无参的成员方法
                 }****
                 4.被引用的方法要满足当前抽象方法的需求
         */
        list.stream().map(String::toUpperCase).forEach(s -> System.out.println(s));




////////////////////////////////////////////////////////////////////////
        System.out.println();
        System.out.println("------------------使用数组的构造方法: 数组的类型要跟流中类型要一致---------------------------");
       //要求:将集合的数据收集到数组中
        ArrayList<Integer> intList=new ArrayList<>();
        Collections.addAll(intList,1,2,3,4,5,6,7,8,9);



        System.out.println("--- //原始写法:----");
        Integer[] ints = intList.stream().toArray(new IntFunction<Integer[]>() {
            @Override
            public Integer[] apply(int value) {
                return new Integer[value];
            }
        });

        for (Integer anInt : ints) {
            System.out.print(anInt+"\t");
        }
        System.out.println();

        System.out.println("--- //方法引用【数组】写法:----");
        Integer[] integers = intList.stream().toArray(Integer[]::new);

        for (Integer an : integers) {
            System.out.print(an+"\t");
        }

    }
}

  

posted @ 2022-12-10 11:18  唯易人生  阅读(46)  评论(0)    收藏  举报