JAVA基础一:java新特性

1 Lambda

  1. lambda 表达式可以简化了以前的一大堆繁琐的操作,让我们代码看起来更加简洁。

  2. 关于箭头操作符

    1. Java8 中引入了一个新的操作符 ->,该操作符称为箭头操作符或者Lambda操作符,箭头操作符将Lambda表达式拆分成两部分:左侧是Lambda表达式的参数列表,对应的是接口中抽象方法的参数列表;右侧是Lambda表达式中所需要执行的功能(Lambda体),对应的是对抽象方法的实现。
    2. Lambda表达式的实质是:对接口的实现
    3. 注:函数式接口只能有一个抽象方法
  3. 语法

    • 总结:左右遇一括号省、左侧推断类型省。即箭头左边有一个参数时小括号可以省略、箭头右边有一条语句时花括号可以省略;左侧形参不用写数据类型、编译器可以自动推断。样例代码如下
    public class TestLambda {
    
        /**
         * 无参数、无返回类型
         */
        @Test
        public void test1() {
            // jdk7 之前必须定义为 final 下面的匿名内部类才能访问
            final int num = 2; 
    
            // 法一:以前方法
            Runnable runnable = new Runnable() {
                @Override
                public void run() {
                    System.out.println("普通方法:num = " + num);
                }
            };
            runnable.run();
    
            // 法二:lamdba表达式
            Runnable runnable1 = () -> System.out.println("lamdba表达式:num = " + num);
            runnable1.run();
        }
    
        /**
         * 一个参数、无返回值
         * (只有一个参数时箭头前面的小括号可省略)
         */
        @Test
        public void test2() {
            // Consumer<String> consumer = (x) -> System.out.println(x);
            Consumer<String> consumer = x -> System.out.println(x);
            consumer.accept("lambda测试");
        }
    
        /**
         * 多个参数、Lamdba体多条语句、有返回值
         * (参数要使用小括号括起来、函数体要使用花括号、且要加上return语句)
         */
        @Test
        public void test3() {
            Comparator<Integer> comparator = (x, y) -> {
                int compare = Integer.compare(y, x); // 降序
                return compare;
            };
    
            Integer[] nums = {2, 1, 7, 3, 8, 9, 4, 6};
            Arrays.sort(nums, comparator);
            System.out.println(Arrays.toString(nums));
        }
    
        /**
         * 两个参数、有返回值、但只有一条语句
         * (花括号省略、return省略)
         */
        @Test
        public void test4() {
            Comparator<Integer> comparator = (x, y) -> Integer.compare(x, y); // 升序
    
            Integer[] nums = {2, 1, 7, 3, 8, 9, 4, 6};
            Arrays.sort(nums, comparator);
            System.out.println(Arrays.toString(nums));
        }
    
        /**
         * Lambda表达式的参数列表的数据类型可以省略不写,因为JVM编译器通过上下文推断出数据类型,即"类型推断"
         *
         * (Integer x,Integer y ) -> Integer.compare(x,y)
         * 可以简写成(x,y) -> Integer.compare(x,y);
         */
    }
    

2 函数式接口

  • 若接口中只有一个抽象方法的接口称为函数式接口;Java 8 新增加了一种特殊的注解 @FunctionalInterface,该注解会自动判断你的接口中是否只有一个抽象方法,如果多于一个抽象方法就会报错。

  • java8 四大内置函数式接口如下

    接口作用
    Supplier< T >供给型接口:T get()
    Consumer< T >消费型接口:void accept(T t)
    Function< T , R >函数式接口:R apply (T t)
    Predicate< T >断言形接口:boolean test(T t)

2.1 Supplier< T >

public class TestSupplier {

    @Test
    public void test() {
        ArrayList<Integer> result = getNumList(10, () -> (int) (Math.random() * 100));
        System.out.println(result);
    }

    //需求,产生指定个数的整数,并放入集合中
    private ArrayList<Integer> getNumList(int num, Supplier<Integer> supplier) {
        ArrayList<Integer> list = new ArrayList<>();
        for (int i = 0; i < num; i++) {
            Integer element = supplier.get();
            list.add(element);
        }
        return list;
    }
}

2.2 Consumer< T >

Consumer

  1. Consumer<T> 样例

    package funcInterface;
    
    import org.junit.Test;
    
    import java.util.function.Consumer;
    
    public class TestConsumer {
        /**
         * 单步 debug 调试运行过程
         * <p>
         * 由 test1() 开始运行
         * 然后进入到 apply() 函数,此时 num=1000.0,然后执行 consumer.accept() 方法
         * 接着再去执行 `num -> System.out.println("消费 " + num + " 元")` 这行代码
         * 【可以把该行代码看成 `consumer.accept(num);` 的实现】
         * <p>
         * 注:接受lambda表达式的应该是一个函数式接口,且该接口只能有一个接口方法、若是有多个会报错
         * 自己将来定义时需要特别注意,不能有多个接口方法!
         */
        @Test
        public void test1() {
            apply(1000, num -> System.out.println("消费 " + num + " 元"));
        }
    
        public void apply(double num, Consumer<Double> consumer) {
            consumer.accept(num);
        }
    }
    
  2. 自定义函数接口

    package funcInterface;
    
    import org.junit.Test;
    
    // 自定义接口
    interface MyConsumer<T> {
        void say(T name);
    }
    
    public class TestMyConsumer {
    
        private void apply(String name, MyConsumer<String> consumer) {
            consumer.say(name);
        }
    
        @Test
        public void test() {
            // lambda表达式可以看成是对接口 consumer.say(name) 的实现
            apply("zhangsan", name -> System.out.println("hello, my name is " + name));
        }
    }
    

BiConsumer

2.3 Function < T, R >

Function

  • 样例代码

    package cn;
    
    import org.junit.Test;
    
    import java.util.Arrays;
    import java.util.List;
    import java.util.Map;
    import java.util.function.Function;
    import java.util.stream.Collectors;
    
    public class TestFunction {
    
        /**
         * 测试形参是 Function<T, R>
         * <T> 可以理解为方法入参, <R> 可以理解为方法返回值
         * -----------------------------------------------------------------------------------
         * Function<T, R> 中四个方法的介绍
         * <p>
         * R apply(T t)
         * apply()是将参数代入方法中
         * <p>
         * default <V> Function<V, R> compose(Function<? super V, ? extends T> before)
         * compose()括号中的内容是在调用函数之前运行
         * <p>
         * default <V> Function<T, V> andThen(Function<? super R, ? extends V> after)
         * addThen()括号中的内容是在调用函数之后运行
         * <p>
         * static <T> Function<T, T> identity()
         * identity()直接返回传入的参数【静态方法】
         */
    
        /**
         * 测试基本四种方法
         */
        @Test
        public void test() {
            // apply测试1
            System.out.println(mulFunction.apply(3)); // 结果9
    
            // apply测试2
            List<Integer> list = Arrays.asList(1, 2, 3, 6, 7, 8);
            System.out.println(addFunction.apply(list)); // 结果27
    
            /*
             * compose测试
             * 先执行 subFunction, 即 5-1=4
             * 再执行 mulFunction, 即 4*4=16
             */
            System.out.println(mulFunction.compose(subFunction).apply(5)); // 结果16
    
            /*
             * andThen测试
             * 先执行 mulFunction, 即 5*5=25
             * 再执行 subFunction, 即 25-1=24
             */
            System.out.println(mulFunction.andThen(subFunction).apply(5)); // 结果24
    
            // identity 测试1
            System.out.println(Function.identity().apply(1)); // 结果1
            System.out.println(Function.identity().apply(list)); // 结果[1, 2, 3, 6, 7, 8]
    
            /*
             * identity 测试2
             * 当返回Map的时候,value还是本身,用起来很方便
             */
    
            List<Student> studentList = Arrays.asList(
                    new Student(10001, "张三", 20, "苏州"),
                    new Student(10002, "李四", 29, "北京"),
                    new Student(10003, "王五", 22, "上海"),
                    new Student(10004, "赵六", 26, "郑州"),
                    new Student(10005, "小明", 18, "洛阳"));
            Map<Integer, Student> studentMap = studentList.stream().collect(Collectors
                                               .toMap(Student::getId, Function.identity()));
            studentMap.forEach((id, stu) -> System.out.println(id + ":" + stu.toString()));
            /**
             * 结果
             * 10001:Student [id=10001, name=张三, age=20, address=苏州]
             * 10002:Student [id=10002, name=李四, age=29, address=北京]
             * 10003:Student [id=10003, name=王五, age=22, address=上海]
             * 10004:Student [id=10004, name=赵六, age=26, address=郑州]
             * 10005:Student [id=10005, name=小明, age=18, address=洛阳]
             */
    
        }
    
        /**
         * 测试 Function<T,R> 当形参
         */
        @Test
        public void test2() {
            // 10 + mulFunction.apply(5) = 10 + 5*5 = 10 + 25 = 35
            Integer mulResult = myFunction(10, mulFunction);
            System.out.println("mulResult = " + mulResult); // 结果:mulResult = 35
    
            // 10 + subFunction.apply(5) = 10 + (5-1) = 14
            Integer subResult = myFunction(10, subFunction);
            System.out.println("subResult = " + subResult); // 结果:subResult = 14
    
            /*
             * 重新形参function函数,让直接返回20
             *
             * myFunction 函数中的 `return arg + function.apply(5);`
             * function.apply(5) 不再生效,即达到重写形参function函数的目的
             */
            Integer otherResult1 = myFunction(10, a -> 20);
            System.out.println("otherResult1 = " + otherResult1);  // 结果:otherResult1 = 30
    
            Integer otherResult2 = myFunction(10, a -> 5 * 6);
            System.out.println("otherResult2 = " + otherResult2); // 结果:otherResult2 = 40
    
    
        }
    
        @Test
        public void test3() {
            System.out.println(strHandler("abc", (str) -> str.toUpperCase()));
            System.out.println(strHandler("   abc  ", (str) -> str.trim()));
        }
    
        private Function<Integer, Integer> mulFunction = i -> i * i;
    
        private Function<Integer, Integer> subFunction = a -> a - 1;
    
        private Function<List<Integer>, Integer> addFunction = list -> {
            int sum = 0;
            for (Integer integer : list) {
                sum += integer;
            }
            return sum;
        };
    
        private Integer myFunction(Integer arg, Function<Integer, Integer> function) {
            return arg + function.apply(5);
        }
    
        private String strHandler(String str, Function<String, String> function) {
            return function.apply(str);
        }
    }
    
    
    class Student {
        Integer id;
    
        String name;
    
        Integer age;
    
        String address;
    
        public Integer getId() {
            return id;
        }
    
        public Student() {
    
        }
    
        public Student(Integer id, String name, Integer age, String address) {
            this.id = id;
            this.name = name;
            this.age = age;
            this.address = address;
        }
    
        @Override
        public String toString() {
            return "Student [id=" + id + ", name=" + name + ", age=" + age + ", address=" + address + "]";
        }
    
    }
    

BiFunction

2.4 Predicate< T >

package cn;

import org.junit.Test;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.function.Predicate;


public class TestPredicate {
    @Test
    public void test() {
        List<String> list = Arrays.asList("Hello", "world", "go", "java", "c++", "python", "php");
        List<String> result = filterStr(list, str -> str.length() > 3);
        System.out.println(result);
        // 结果:[Hello, world, java, python]
    }

    private List<String> filterStr(List<String> list, Predicate<String> predicate) {
        ArrayList<String> result = new ArrayList<>();
        for (String str : list) {
            if (predicate.test(str)) {
                result.add(str);
            }
        }
        return result;
    }
}

3 Stream

  • Stream 表示能应用在一组元素上依次执行的操作序列。Stream 操作分为中间操作或者最终操作两种,最终操作返回一特定类型的计算结果,而中间操作返回 Stream 本身,这样我们就可以将多个操作依次串起来。Stream 的创建需要指定一个数据源,比如java.util.Collection 的子类:List 或者 Set,Map 不支持。Stream 的操作可以串行执行或者并行执行。

  • 样例代码

    package cn;
    
    import org.junit.Before;
    import org.junit.Test;
    
    import java.util.*;
    import java.util.stream.Collectors;
    import java.util.stream.Stream;
    
    public class TestStream {
    
        private List<String> list = null;
        private Stream<String> stream = null;
    
        /**
         * 我们可以通过 Collection.stream() 或者 Collection.parallelStream()
         * 来创建一个Stream对象
         */
        @Before
        public void init() {
            list = Arrays.asList("a1", "b1", "c1", "a2", "c2", "a3", "b2", "b3", "c3");
            stream = list.stream(); // 串行执行
            // Stream<String> stream2 = list.parallelStream(); // 并行执行
        }
    
        /**
         * 例一:过滤
         */
        @Test
        public void test1() {
            list.stream().filter(str -> str.startsWith("a")).forEach(System.out::println);
            /**
             * 结果
             * a1
             * a2
             * a3
             */
        }
    
        /**
         * 例二:排序
         */
        @Test
        public void test2() {
            list.stream().sorted((str1, str2) -> str1.hashCode() < str2.hashCode() ? -1 : 1).forEach(System.out::println);
            /**
             * 结果
             * a1
             * a2
             * a3
             * b1
             * b2
             * b3
             * c1
             * c2
             * c3
             */
        }
    
        /**
         * 例三:映射
         */
        @Test
        public void test3() {
            list.stream().map(String::toUpperCase).sorted((str1, str2) -> str1.hashCode() < str2.hashCode() ? -1 : 1).forEach(System.out::println);
            /**
             * 结果
             * A1
             * A2
             * A3
             * B1
             * B2
             * B3
             * C1
             * C2
             * C3
             */
        }
    
    
        /**
         * 例四:计数
         */
        @Test
        public void test4() {
            long count = list.stream().count();
            System.out.println("count = " + count);
            // count = 9
        }
    
        /**
         * Parallel Stream(并行流)
         * Stream有串行和并行两种,串行Stream上的操作是在一个线程中依次完成,而并行Stream则是在多个线程上同时执行。
         * 下面使用串行流和并行流为一个大容器进行排序,比较两者性能。
         */
        @Test
        public void test5() {
            int size = 10000000; // 一千万
            List<String> strList = new ArrayList<>(size);
    
            long startTime0 = System.currentTimeMillis();
            for (int i = 0; i < size; i++) {
                strList.add(UUID.randomUUID().toString());
            }
            long endTime0 = System.currentTimeMillis();
            System.out.println("生成 " + size + " 条数据, 花费" + (endTime0 - startTime0) + "毫秒");
    
            long startTime1 = System.currentTimeMillis();
            strList.stream().sorted((str1, str2) -> str1.hashCode() < str2.hashCode() ? -1 : 1).count();
            long endTime1 = System.currentTimeMillis();
            System.out.println("串行排序 " + size + " 条数据, 花费 " + (endTime1 - startTime1) + "毫秒");
    
    
            long startTime2 = System.currentTimeMillis();
            strList.parallelStream().sorted((str1, str2) -> str1.hashCode() < str2.hashCode() ? -1 : 1).count();
            long endTime2 = System.currentTimeMillis();
            System.out.println("并行排序 " + size + " 条数据, 花费 " + (endTime2 - startTime2) + "毫秒");
    
            /**
             * 结果
             * 生成 10000000 条数据, 花费6741毫秒
             * 串行排序 10000000 条数据, 花费 1毫秒
             * 并行排序 10000000 条数据, 花费 1609毫秒
             *
             * 【自己电脑上并行居然比串行慢?!】
             * 参考链接:https://javakk.com/1914.html
             *
             * 由此可知,并发不一定比单线程快!
             */
        }
    
        /**
         * Collector 和 Collectors
         * <p>
         * Collector 是专门用来作为 Stream 的 collect 方法的参数的
         * 而 Collectors 是作为生产具体 Collector 的工具类
         */
        @Test
        public void test6() {
            List<String> collect = list.stream().collect(Collectors.toList());
            System.out.println(collect);
            /**
             * 结果
             * [a1, b1, c1, a2, c2, a3, b2, b3, c3]
             */
    
            Set<String> set = list.stream().collect(Collectors.toSet());
            TreeSet<String> treeSet = list.stream().collect(Collectors.toCollection(TreeSet::new));
            System.out.println(set);
            System.out.println(treeSet);
            /**
             * 结果
             * [a1, b2, c3, a2, b3, a3, c1, b1, c2]
             * [a1, a2, a3, b1, b2, b3, c1, c2, c3]
             */
    
            // 拼接流中所有字符串
            String str1 = list.stream().collect(Collectors.joining());
            String str2 = list.stream().collect(Collectors.joining(","));
            System.out.println("str1 = " + str1);
            System.out.println("str2 = " + str2);
            /**
             * 结果
             * str1 = a1b1c1a2c2a3b2b3c3
             * str2 = a1,b1,c1,a2,c2,a3,b2,b3,c3
             */
    
    
            /**
             * Collector<T, ?, M> toMap(Function<? super T, ? extends K> keyMapper, Function<? super T, ? extends U> valueMapper,
             *                          BinaryOperator<U> mergeFunction, Supplier<M> mapFactory)
             *
             * Collectors.toMap(e -> "key " + e, e -> "value " + e, (a, b) -> b, HashMap::new)
             * e -> "key " + e,定义 map 的 key 的生成规则
             * e -> "value " + e,定义 map 的 value 的生成规则
             * (a, b) -> b,表示冲突的解决方案,如果键a和键b冲突了则该键键值取b的
             * HashMap::new 定义了生成的 map 为 HashMap
             */
            HashMap<String, String> map = list.stream().collect(Collectors.toMap(e -> "key " + e, e -> "value " + e, (a, b) -> b, HashMap::new));
            for (String key : map.keySet()) {
                System.out.println("Key = " + key + ", value = " + map.get(key));
            }
            /**
             * 结果
             * Key = key c1, value = value c1
             * Key = key c3, value = value c3
             * Key = key b2, value = value b2
             * Key = key a1, value = value a1
             * Key = key c2, value = value c2
             * Key = key b1, value = value b1
             * Key = key a3, value = value a3
             * Key = key b3, value = value b3
             * Key = key a2, value = value a2
             */
        }
    }
    

参考链接

  1. java 新特性总结
  2. Lambda表达式总结
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值