Java 8 新特性

心已赠人 2022-07-14 03:59 304阅读 0赞

Java 8 新特性


lambda表达式

  1. Lambda表达式(也称为闭包),Lambda允许把函数作为一个方法的参数.
  2. Lambda 表达式由三个部分组成:
  3. 第一部分:一个括号内用逗号分隔的形式参数,参数是函数式接口里面方法的参数
  4. 第二部分:一个箭头符号:->
  5. 第三部分:方法体,可以是表达式和代码块
  6. Lambda Expressions syntax is (argument) -> (body)

函数式接口

  1. 如果一个接口定义个唯一一个抽象方法,那么这个接口就称为函数式接口.通常使用@FunctionalInterface注解
  2. 默认方法与静态方法并不影响函数式接口的契约,可以任意使用.
  3. Runnable接口是一个典型的函数式接口.
  4. Runnable runnable = () ->
  5. {
  6. System.out.println("new way create Runnable instance");
  7. };
  8. @FunctionalInterface
  9. public interface FunctionalDefaultMethods {
  10. void method();
  11. default void defaultMethod() {
  12. }
  13. }

例子演示

  1. 函数式接口结合lambda表达式
  2. @FunctionalInterface
  3. public interface FunctionInterface
  4. {
  5. int operate(int a, int b);
  6. }
  7. public class MainApp
  8. {
  9. public static void main(String[] args)
  10. {
  11. FunctionInterface addFunction = (a, b) -> a + b;
  12. FunctionInterface subFunction = (a, b) -> a - b;
  13. FunctionInterface mulFunction = (a, b) -> a * b;
  14. FunctionInterface divFunction = (a, b) -> a / b;
  15. System.out.println(addFunction.operation(10, 5));
  16. System.out.println(subFunction.operation(10, 5));
  17. System.out.println(mulFunction.operation(10, 5));
  18. System.out.println(divFunction.operation(10, 5));
  19. }
  20. }

  1. 使用forEach方法
  2. @Test
  3. public void testForEach()
  4. {
  5. List<String> languages = Arrays.asList("java", "C", "C++", "C#", "JavaScript");
  6. languages.forEach(e ->
  7. {
  8. System.out.print(e + " , ");
  9. });
  10. List<String> list = new ArrayList<>();
  11. languages.forEach(e ->
  12. {
  13. list.add(e);
  14. });
  15. System.out.println(list);
  16. }

  1. 使用lambda表达式应用Runnable接口
  2. Runnable runnable = () ->
  3. {
  4. System.out.println(Thread.currentThread().getName());
  5. System.out.println("hello world");
  6. };
  7. new Thread(runnable).start();

Stream API

  1. A new java.util.stream perform filter/map/reduce like operations with the collection.
  2. Stream流操作是Java 8对集合操作的性能提升手段,记住Stream操作是不会改变原来集合的数据的.

  1. streamparallelStream方法
  2. @Test
  3. public void testStreamAPI()
  4. {
  5. List<Integer> myList = new ArrayList<>();
  6. for (int i = 0; i < 5; i++)
  7. myList.add(i);
  8. // 串行计算
  9. List<Integer> sequentialList = myList.stream().filter(num -> num > 2).collect(Collectors.toList());
  10. // 并行计算(在大集合和多CPU场景下可以发挥更高性能)
  11. List<Integer> parallelList = myList.parallelStream().filter(num -> num > 2).collect(Collectors.toList());
  12. System.out.println(myList);
  13. System.out.println(sequentialList);
  14. System.out.println(parallelList);
  15. }
  16. 备注:
  17. Notice that parallel processing values are not in order,
  18. so parallel processing will be very helpful while working with huge collections.

  1. 测试Stream filter方法
  2. @Test
  3. public void testFilter()
  4. {
  5. List<String> languages = Arrays.asList("java", "C", "C++", "C#", "JavaScript", null);
  6. languages.stream().filter(e -> e != null && e.length() > 3).forEach(e ->
  7. {
  8. System.out.println(e);
  9. });
  10. List<String> list = languages.stream().filter(e -> e != null && e.length() > 2).collect(Collectors.toList());
  11. System.out.println(list);
  12. }

  1. 测试Stream map方法(映射)
  2. @Test
  3. public void testStreamMap()
  4. {
  5. List<String> languages = Arrays.asList("java", "C", "C++", "C#", "JavaScript", null);
  6. List<String> list = languages.stream().filter(e -> e != null)
  7. .map(e -> e.toUpperCase() + "-language").collect(Collectors.toList());
  8. System.out.println(list);
  9. }

  1. 测试Stream reduce方法(归约)
  2. @Test
  3. public void testReduce()
  4. {
  5. List<String> languages = Arrays.asList("java", "C", "C++", "C#", "JavaScript", null);
  6. String count = languages.stream().filter(e -> e != null)
  7. .map(e -> e.toUpperCase()).reduce((a, b) -> a = a + b).get();
  8. System.out.println(count);
  9. }

  1. 测试Stream sorted方法(排序)
  2. @Test
  3. public void testStreamSort()
  4. {
  5. List<String> languages = Arrays.asList("java", "C", "C++", "C#", "JavaScript");
  6. //顺序排
  7. List<String> orderSortLanguage = languages.stream().sorted().collect(Collectors.toList());
  8. //倒序排
  9. List<String> reverseSortLanguage = languages.stream().sorted(Comparator.reverseOrder()).collect(Collectors.toList());
  10. System.out.println(languages);
  11. System.out.println(orderSortLanguage);
  12. System.out.println(reverseSortLanguage);
  13. }

  1. 测试Stream count方法(求集合元素个数)
  2. Stream<Integer> numbers1 = Stream.of(1,2,3,4,5);
  3. System.out.println("Number of elements in stream="+numbers1.count()); //5

  1. 测试Stream forEach方法
  2. @Test
  3. public void testForEach()
  4. {
  5. List<String> languages = Arrays.asList("java", "C", "C++", "C#", "JavaScript");
  6. languages.forEach(e ->
  7. {
  8. System.out.print(e + " , ");
  9. });
  10. }

  1. 测试Stream match方法
  2. @Test
  3. public void testMatch()
  4. {
  5. List<String> languages = Arrays.asList("java", "C", "C++", "C#", "JavaScript");
  6. boolean jLanguage = languages.stream().allMatch(e -> e.startsWith("j"));
  7. System.out.println(jLanguage);
  8. }

  1. 测试Stream findFirst方法
  2. @Test
  3. public void testFindFirst()
  4. {
  5. Stream<String> names4 = Stream.of("Pankaj", "Amit", "David", "Lisa");
  6. Optional<String> firstNameWithD = names4.filter(i -> i.startsWith("D")).findFirst();
  7. if (firstNameWithD.isPresent())
  8. {
  9. System.out.println("First Name starting with D=" + firstNameWithD.get()); // David
  10. }
  11. }

  1. 创建流
  2. 1、使用Stream的静态方法of(T ...value)创建流
  3. Stream<Integer> stream = Stream.of(1, 2, 3, 4);
  4. Stream<Integer> stream = Stream.of(new Integer[]{1,2,3,4});
  5. 2、使用Collectionstream()或parallelStream()创建流
  6. Collection<String> collection = new ArrayList<>();
  7. Stream<String> sequentialStream=collection.stream();
  8. Stream<String> parallelStream=collection.parallelStream();
  9. 3、使用Stream.generate()和Stream.iterate()创建流
  10. Stream<String> stream1 = Stream.generate(() -> {return "abc";});
  11. Stream<String> stream2 = Stream.iterate("abc", (i) -> i);
  12. 4、使用Arrays.stream()和String.chars()创建流
  13. LongStream longStream = Arrays.stream(new long[]{1,2,3,4});
  14. IntStream intStream = "abc".chars();

  1. Stream转换为集合或数组
  2. 1 使用collect()方法从Stream中获得ListMapSet.
  3. Stream<Integer> intStream = Stream.of(1,2,3,4);
  4. List<Integer> intList = intStream.collect(Collectors.toList());
  5. System.out.println(intList); //prints [1, 2, 3, 4]
  6. intStream = Stream.of(1,2,3,4); //stream is closed, so we need to create it again
  7. Map<Integer,Integer> intMap = intStream.collect(Collectors.toMap(i -> i, i -> i+10));
  8. System.out.println(intMap); //prints {1=11, 2=12, 3=13, 4=14}
  9. 2、使用toArray()方法从Stream中获得数组
  10. Stream<Integer> intStream = Stream.of(1,2,3,4);
  11. Integer[] intArray = intStream.toArray(Integer[]::new);
  12. System.out.println(Arrays.toString(intArray)); //prints [1, 2, 3, 4]

相关概念

Java 8 Stream API 常用的函数式接口

Function and BiFunction

  1. Function represents a function that takes one type of argument and returns another type of argument.
  2. Function<T, R>
  3. BiFunction<T, U, R>

  1. Stream 方法
  2. <R> Stream<R> map(Function<? super T, ? extends R> mapper)
  3. IntStream mapToInt(ToIntFunction<? super T> mapper)
  4. IntStream flatMapToInt(Function<? super T, ? extends IntStream> mapper)
  5. <A> A[] toArray(IntFunction<A[]> generator)
  6. <U> U reduce(U identity, BiFunction<U, ? super T, U> accumulator, BinaryOperator<U> combiner)

Predicate and BiPredicate

  1. It represents a predicate against which elements of the stream are tested.
  2. This is used to filter elements from the java stream.
  3. Just like Function, there are primitive specific interfaces for int, long and double.
  4. Predicate<T>
  5. BiPredicate<T, U>

  1. Stream 方法:
  2. Stream<T> filter(Predicate<? super T> predicate)
  3. boolean anyMatch(Predicate<? super T> predicate)
  4. boolean allMatch(Predicate<? super T> predicate)
  5. boolean noneMatch(Predicate<? super T> predicate)

Consumer and BiConsumer

  1. It represents an operation that accepts a single input argument and returns no result.
  2. It can be used to perform some action on all the elements of the java stream.
  3. Consumer<T>
  4. BiConsumer<T, U>

  1. Stream 方法:
  2. Stream<T> peek(Consumer<? super T> action)
  3. void forEach(Consumer<? super T> action)
  4. void forEachOrdered(Consumer<? super T> action)

Supplier

  1. Supplier represent an operation through which we can generate new values in the stream.
  2. Supplier<T>

  1. Stream 方法
  2. public static<T> Stream<T> generate(Supplier<T> s)
  3. <R> R collect(Supplier<R> supplier,BiConsumer<R, ? super T> accumulator,BiConsumer<R, R> combiner)

java.util.Optional

  1. Java Optional is a container object which may or may not contain a non-null value.
  2. If a value is present, isPresent() will return true and get() will return the value.

  1. Stream 方法
  2. Optional<T> reduce(BinaryOperator<T> accumulator)
  3. Optional<T> min(Comparator<? super T> comparator)
  4. Optional<T> max(Comparator<? super T> comparator)
  5. Optional<T> findFirst()
  6. Optional<T> findAny()

Java 8 日期类型

  1. 针对java日期类型的处理不便,java 8提供了新的日期支持.

参考

1、http://www.journaldev.com/2389/java-8-features-with-examples
2、http://www.journaldev.com/2752/java-8-interface-changes-static-method-default-method
3、http://www.journaldev.com/2763/java-8-functional-interfaces
4、http://www.journaldev.com/2774/java-8-stream
5、http://www.journaldev.com/2800/java-8-date-localdate-localdatetime-instant

发表评论

表情:
评论列表 (有 0 条评论,304人围观)

还没有评论,来说两句吧...

相关阅读

    相关 Java 8特性

    JAVA8 十大新特性 1:接口的默认方法 Java 8允许我们给接口添加一个非抽象的方法实现,只需要使用 default关键字即可,这个特征又叫做扩展方法,示例如下:

    相关 java8特性

    对于Java开发者来说,Java8的版本显然是一个具有里程碑意义的版本,蕴含了许多令人激动的新特性,如果能利用好这些新特性,能够大大提升我们的开发效率。Java8的函数式编程能

    相关 Java 8 特性

    Java 8 新特性 Java 8 (又称为 jdk 1.8) 是 Java 语言开发的一个主要版本。 Oracle 公司于 2014 年 3 月 18 日发布 Java...