非常简单且实用的函数式编程(国庆day1)

函数式:用Lambda表达式实现函数的方式

1 什么时候使用函数式编程?

1.1 集合的操作

1.1.1 转换

list set map之间转换

1.1.2 聚合操作

count:获取数据数量
max:获取按照规则约定的最大值
min:获取按照规则约定的最小值
avg:获取平均值

1.1.3 循环处理

foreach:对数据进行循环处理

1.1.4 转换为String

joining:字符串数据指定分隔符

1.1.5 分组

groupingBy:按照特定功能处理分组

1.1.6 获取数组

toArray:数据转换为Object数组

1.2 Stream的操作

1.2.1 过滤

filter:按照规则筛选数据
distinct:过滤掉相同的数据

1.2.2 转换

map:接收一个T,返回一个R
flatMap:处理Stream嵌套问题

1.2.3 其他操作

skip:忽略前n条数据
limit:限制只需要前n条数据
sorted:将数据排序

1.3 Optional的操作

1.3.1 检测是否为空

isPresent:存在返回true
isEmpty:为空返回true

1.3.2 条件运算

ifPresent:存在则执行

1.3.3 默认值

orElse:当Optional为空时的的默认值

1.3.4 获取值

get:不为空时,获取数据

1.3.5 过滤

filter:对数据进行过滤

1.4 函数接口

1.4.1 Predicate

有输入且输出为布尔值

1.4.2 Function

有输入且有输出

1.4.3 Supplier

有输出没有输入

1.4.4 Consumer

有输入且没有输出

1.4.5 Operator

输入和输出同一类型

1.4.6 Comparator

输入两个值且输出为布尔值

1.5 方法引用

1.5.1 构造函数引用

::new

1.5.2 静态方法的引用

Integer:: toString

1.5.3 实例方法引用

person:: getName

1.5.4 引用任意对象的方法

forEach(person:: getName)

1.6 lambda表达式使用

()输入参数->()返回值

2 集合操作示例

public class _03finalStream {
    public static void main(String[] args) {
        List<Person> people = Arrays.asList(new Person("zhangsan", "男"),
                new Person("lisi", "男"),
                new Person("xiaohong", "女"));
        /**
         * 聚合操作
         */
        //数量
        people.stream().count();
        //最大值
        people.stream().max(Comparator.comparing(Person::getWeight));
        /**
         * 循环
         */
        people.stream().forEach(System.out::println);
        /**
         * 匹配
         */
        //全匹配
        people.stream().allMatch(Person::isMale);
        //任意匹配
        people.stream().anyMatch(Person::isMale);
        //不匹配
        people.stream().noneMatch(Person::isMale);
        /**
         * 查找
         */
        //获取任意数据
        Person person = people.stream().findAny().get();
        //获取第一条数据
        Person person1 = people.stream().findFirst().get();
        /**
         * 获取数组
         */
        Object[] peopleArray = people.stream().toArray();
        /**
         * 累计聚合操作
         */
        Integer r1 = Stream.of(1, 2, 3).reduce((a, b) -> a + b).get();


        /**
         * collect
         */
        Stream<String> nameStream = Stream.of("zhangsan", "lisi");
        //转为集合
        List<String> nameList = nameStream.collect(Collectors.toList());
        // Set<String> nameSet = nameStream.collect(Collectors.toSet());
        //转为String
        // String nameString = nameStream.collect(Collectors.joining(","));
        //聚合操作
        //数量
        // Long nameCount = nameStream.collect(Collectors.counting());
        //最大值
        ///   nameStream.collect(Collectors.maxBy(Comparator.comparing(String::length))).get();
        //平均值
        //  Double nameLength = nameStream.collect(Collectors.averagingLong(String::length));
        //排序,最大值,最小值,平均值,数量,分组
        List<Integer> numList = Arrays.asList(3, 2, 1, 4, 8, 6, 7);
        Stream<Integer> numStream = numList.stream();
        numStream.sorted(Comparator.comparing(Integer::intValue)).forEach(System.out::println);
        IntSummaryStatistics numSummary = numStream.collect(Collectors.summarizingInt(Integer::intValue));
        System.out.println(numSummary.getMax() + " " + numSummary.getMin() + " " + numSummary.getAverage() + " " + numSummary.getCount());
        Map<Integer, List<Integer>> map = numStream.collect(Collectors.groupingBy(Integer::intValue));

        /**
         * 生成map
         */
        Map<Integer, Integer> map1 = numStream.collect(Collectors.toMap(Function.identity(), Integer::intValue));


    }

}

3 Stream操作示例

public class _02IntermediateStream {
    public static void main(String[] args) {

        /**
         * filter
         */
        List<Person> people = Arrays.asList(new Person("zhangsan", "男"),
                new Person("lisi", "男"),
                new Person("xiaohong", "女"));

        //1 函数接口
        people.stream().filter(person -> person.getGender().equals("男"))
                .forEach(person -> System.out.println(person));

        //2 方法引用
        people.stream().filter(Person::isMale).forEach(System.out::println);

        /**
         * distinct
         */
        people.stream().distinct()
                .forEach(System.out::println);
        people.stream().distinct()
                .filter(person -> person.getGender().equals("男"))
                .forEach(System.out::println);

        /**
         * map
         */
        Stream<Integer> nameLength = people.stream()
                .map(Person::getName)
                .map(String::length);

        /**
         * flatMap:解决stream嵌套问题
         */
        List<Person> people1 = Arrays.asList(new Person("zhangsan", "man", 100));
        List<Person> people2 = Arrays.asList(new Person("lisi", "woman", 200));
        List<List<Person>> peopleList = Arrays.asList(people1, people2);
        /**
         * 使用map需要处理嵌套的Stream
         */
        peopleList.stream()
                .map(Collection::stream)
                .forEach(personStream -> personStream.forEach(System.out::println));

        /**
         * 将一个流转为两个流,然后再合成为一个流
         */
        peopleList.stream()
                .flatMap(Collection::stream)
                .forEach(System.out::println);

        /**
         * 其他操作
         */
        /**
         * 忽略前N条
         */
        people1.stream().skip(1).forEach(System.out::println);
        /**
         * 只取前N条
         */
        people1.stream().limit(1).forEach(System.out::println);
        /**
         * 将数据排序
         */
        people1.stream().sorted(Comparator.comparing(Person::getWeight)).forEach(System.out::println);


    }
}

4 Optioanl操作示例

public class _01getOptional {
    public static void main(String[] args) {
        Optional<Object> emptyOptional = Optional.empty();
        Optional<String> stringOptional = Optional.of("zhangsan");
        String str1 = "zhangsan";
        String str2 = null;
        Optional<String> stringOptional1 = Optional.ofNullable(str1);
        Optional<String> nullOptional2 = Optional.ofNullable(str2);

        //检查是否存在
        System.out.println(stringOptional.isPresent());
        System.out.println(nullOptional2.isPresent());
        System.out.println(nullOptional2.isEmpty());
        //条件运算
        stringOptional1.ifPresent(System.out::println);
        //默认值
        nullOptional2.orElse("lisi");
        //获得值
        if (nullOptional2.isPresent()) {
            nullOptional2.get();
        }
        //数据过滤
        nullOptional2.filter(s -> s.equals("zhangsan")).isPresent();
        //转换处理
        String str2 = nullOptional2.map(s -> "map" + s).get();
    }
} 

5 函数式接口

5.1 Predicate

public class _01Predicate {
    public static void main(String[] args) {

        /**
         * i>0
         */
        IntPredicate greaterThan0 = i -> i > 0;
        System.out.println(greaterThan0.test(10));

        /**
         * negate: i<=0
         */
        IntPredicate negate = greaterThan0.negate();
        System.out.println(negate.test(10));

        /**
         * and: i>0 and i<100
         */
        IntPredicate lessThan100 = i -> i <= 100;
        IntPredicate and = greaterThan0.and(lessThan100);
        System.out.println(and.test(10));

        /**
         * or: i>0 or i>0 or i<100
         */
        IntPredicate or = greaterThan0.or(lessThan100);
        System.out.println(or.test(-100));

        /**
         * BiPredicate:两个参数
         */
        BiPredicate<String,Integer> isLenThanGivenLen = (str, len) -> str.length() > len;
        System.out.println(isLenThanGivenLen.test("123",3));
    }
}

5.2 Function

public class _02Function {
    public static void main(String[] args) {
        /**
         * apply
         */
        Function<String, Integer> lengthFunction = str -> str.length();
        System.out.println(lengthFunction.apply("123"));

        Function<Integer, Integer> plusFunction = x -> x + x;
        Function<Integer,Integer> multiFunction = x -> x * x;

        /**
         * andThen
         */
        Function<Integer, Integer> andThen = plusFunction.andThen(multiFunction);
        System.out.println(andThen.apply(2));

        /**
         * compose
         */
        Function<Integer, Integer> compose = plusFunction.compose(multiFunction);
        System.out.println(compose.apply(2));

        /**
         * 参数固化
         */
        IntFunction<Integer> intPlusFunction = x -> x + x;
        System.out.println(intPlusFunction.apply(2));

        /**
         * 返回值固化
         */
        ToIntFunction<Integer> toIntPlusFunction = x -> x + x;
        System.out.println(toIntPlusFunction.applyAsInt(2));

        /**
         * 参数和返回值都固化
         */
        IntToLongFunction intToLongPlusFunction = x -> x + x;
        System.out.println(intToLongPlusFunction.applyAsLong(2));

        /**
         * 两个参数
         */
        BiFunction<String,String,Integer> biFunction = (str1, str2) -> str1.length() + str2.length();
        System.out.println(biFunction.apply("123","456"));
    }
}

5.3 Consumer

public class _03Consumer {
    public static void main(String[] args) {
        Consumer<String> lengthConsumer = str -> System.out.println(str.length());
        lengthConsumer.accept("123");
    }
}

5.4 Supplier

public class _04Supplier {
    public static void main(String[] args) {
        Supplier<Long> supplier = () -> System.currentTimeMillis();
        System.out.println(supplier.get());

    }
}

5.5 Operator

public class _05Operator {
    public static void main(String[] args) {
        IntUnaryOperator operatorFunction = x -> x + x;
        System.out.println(operatorFunction.applyAsInt(2));
    }

}

5.6 Comparator

public class _06Comparator {

    public static void main(String[] args) {
        Comparator<Integer> compareFunction = (num1, num2) -> num1.compareTo(num2);
        System.out.println(compareFunction.compare(1,2));
    }
}

6 方法引用

6.1 Constructor

public class _01Constructor {

    public static void main(String[] args) {
        //1 无参数构造,只生产不消费
        Supplier<Person> emptyConstructor = Person::new;
        Person person = emptyConstructor.get();
        person.setName("zhangsan");
        System.out.println(person);

        //2 一个参数构造,既生产又消费
        Function<String, Person> nameConstructor = Person::new;
        Person person1 = nameConstructor.apply("zhangsan");
        System.out.println(person1);


        //3 两个参数构造,既生产又消费
        BiFunction<String, String, Person> nameAndGenderConstructor = Person::new;
        Person person2 = nameAndGenderConstructor.apply("zhangsan", "man");
        System.out.println(person2);
    }
}

6.2 Static

public class _02Static {
    public static void main(String[] args) {
        /**
         * toString方法是Integer类的静态方法
         */
        IntFunction<String> intToStringFunction = Integer::toString;
        System.out.println(intToStringFunction.apply(123));
    }
}

6.3 Instance

public class _03Instance {
    public static void main(String[] args) {
        Person person = new Person("zhangsan", "man", 100);
        Consumer<String> walkConsumer = person::walk;
        walkConsumer.accept("上海路");
    }
}

6.4 AnyInstance

public class _04AnyInstance {
    public static void main(String[] args) {
        List<Person> people = Arrays.asList(new Person("zhagnsan", "man", 123)
                , new Person("lisi", "man", 456));
        people.forEach(Person::sayName);
    }
}

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值