博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
java组合与继承始示例_Java 8特性与示例
阅读量:2533 次
发布时间:2019-05-11

本文共 16583 字,大约阅读时间需要 55 分钟。

java组合与继承始示例

Java 8 was released on 18th March 2014, so it’s high time to look into Java 8 Features. In this tutorial, we will look into Java 8 features with examples.

Java 8于2014年3月18日发布,因此该研究Java 8功能了。 在本教程中,我们将通过示例研究Java 8功能。

Java 8功能 (Java 8 Features)

Some of the important Java 8 features are;

Java 8的一些重要功能是:

Let’s have a brief look on these Java 8 features. I will provide some code snippets for better understanding, so if you want to run programs in Java 8, you will have to setup Java 8 environment by following steps.

让我们简要了解一下这些Java 8功能。 我将提供一些代码片段以更好地理解,因此,如果要在Java 8中运行程序,则必须按照以下步骤设置Java 8环境。

  • and install it. Installation is simple like other java versions. JDK installation is required to write, compile and run the program in Java.

    并安装 。 像其他Java版本一样,安装也很简单。 要使用Java编写,编译和运行程序,必须安装JDK。
  • Download latest Eclipse IDE, it provides support for java 8 now. Make sure your projects build path is using Java 8 library.

    下载最新的Eclipse IDE,它现在支持Java 8。 确保您的项目构建路径正在使用Java 8库。
to get heavy discount on the course. 可获得该课程的大幅折扣。
  1. Iterable接口中的forEach()方法 (forEach() method in Iterable interface)

    Whenever we need to traverse through a Collection, we need to create an Iterator whose whole purpose is to iterate over and then we have business logic in a loop for each of the elements in the Collection. We might get if iterator is not used properly.

    Java 8 has introduced forEach method in java.lang.Iterable interface so that while writing code we focus on business logic only. forEach method takes java.util.function.Consumer object as argument, so it helps in having our business logic at a separate location that we can reuse. Let’s see forEach usage with simple example.

    package com.journaldev.java8.foreach;import java.util.ArrayList;import java.util.Iterator;import java.util.List;import java.util.function.Consumer;import java.lang.Integer;public class Java8ForEachExample {	public static void main(String[] args) {				//creating sample Collection		List
    myList = new ArrayList
    (); for(int i=0; i<10; i++) myList.add(i); //traversing using Iterator Iterator
    it = myList.iterator(); while(it.hasNext()){ Integer i = it.next(); System.out.println("Iterator Value::"+i); } //traversing through forEach method of Iterable with anonymous class myList.forEach(new Consumer
    () { public void accept(Integer t) { System.out.println("forEach anonymous class Value::"+t); } }); //traversing with Consumer interface implementation MyConsumer action = new MyConsumer(); myList.forEach(action); }}//Consumer implementation that can be reusedclass MyConsumer implements Consumer
    { public void accept(Integer t) { System.out.println("Consumer impl Value::"+t); }}

    The number of lines might increase but forEach method helps in having the logic for iteration and business logic at separate place resulting in higher separation of concern and cleaner code.

    每当我们需要遍历Collection时,就需要创建一个Iterator其整个目的是进行迭代,然后针对Collection中的每个元素将业务逻辑循环存在。 如果迭代器使用不正确,我们可能会收到 。

    Java 8在java.lang.Iterable接口中引入了forEach方法,因此在编写代码时,我们仅关注业务逻辑。 forEach方法将java.util.function.Consumer对象作为参数,因此有助于将我们的业务逻辑放在可重用的单独位置。 让我们通过简单的示例查看forEach用法。

    行数可能会增加,但是forEach方法有助于将迭代逻辑和业务逻辑放在单独的位置,从而使关注点和更清晰的代码更加分离。

  2. 接口中的默认方法和静态方法 (default and static methods in Interfaces)

    If you read forEach method details carefully, you will notice that it’s defined in Iterable interface but we know that interfaces can’t have method body. From Java 8, interfaces are enhanced to have method with implementation. We can use default and static keyword to create interfaces with method implementation. forEach method implementation in Iterable interface is:

    default void forEach(Consumer
    action) { Objects.requireNonNull(action); for (T t : this) { action.accept(t); } }

    We know that Java doesn’t provide because it leads to Diamond Problem. So how it will be handled with interfaces now, since interfaces are now similar to abstract classes. The solution is that compiler will throw exception in this scenario and we will have to provide implementation logic in the class implementing the interfaces.

    package com.journaldev.java8.defaultmethod;@FunctionalInterfacepublic interface Interface2 {	void method2();		default void log(String str){		System.out.println("I2 logging::"+str);	}}

    Notice that both the interfaces have a common method log() with implementation logic.

    As you can see that Interface1 has static method implementation that is used in MyClass.log() method implementation. Java 8 uses default and static methods heavily in and default methods are added so that our code remains backward compatible.

    If any class in the hierarchy has a method with the same signature, then default methods become irrelevant. Since any class implementing an interface already has Object as a superclass, if we have equals(), hashCode() default methods in the interface, it will become irrelevant. That’s why for better clarity, interfaces are not allowed to have Object default methods.

    For complete details of interface changes in Java 8, please read .

    如果仔细阅读forEach方法的详细信息,您会注意到它是在Iterable接口中定义的,但是我们知道接口不能具有方法主体。 从Java 8开始,接口已增强为具有实现的方法。 我们可以使用defaultstatic关键字来创建具有方法实现的接口。 Iterable接口中的forEach方法实现为:

    default void forEach(Consumer
    action) { Objects.requireNonNull(action); for (T t : this) { action.accept(t); } }

    我们知道Java不会提供因为它会导致Diamond问题 。 由于接口现在类似于抽象类,因此现在如何使用接口处理它。 解决的办法是在这种情况下编译器将引发异常,我们将不得不在实现接口的类中提供实现逻辑。

    package com.journaldev.java8.defaultmethod;@FunctionalInterfacepublic interface Interface2 {	void method2();		default void log(String str){		System.out.println("I2 logging::"+str);	}}

    注意,两个接口都有一个带有实现逻辑的通用方法log()。

    如您所见, Interface1具有在MyClass.log()方法实现中使用的静态方法实现。 Java 8在大量使用默认静态方法,并且添加了默认方法,以便我们的代码保持向后兼容。

    如果层次结构中的任何类都具有具有相同签名的方法,则默认方法将变得无关紧要。 由于任何实现接口的类都已经具有Object作为超类,因此如果接口中具有equals(),hashCode()默认方法,它将变得无关紧要。 这就是为什么为了更清楚起见,不允许接口具有Object默认方法。

    有关Java 8接口更改的完整详细信息,请阅读 。

  3. 功能接口和Lambda表达式 (Functional Interfaces and Lambda Expressions)

    If you notice above interfaces code, you will notice @FunctionalInterface . Functional interfaces are new concept introduced in Java 8. An interface with exactly one abstract method becomes Functional Interface. We don’t need to use @FunctionalInterface annotation to mark an interface as Functional Interface. @FunctionalInterface annotation is a facility to avoid accidental addition of abstract methods in the functional interfaces. You can think of it like and it’s best practice to use it. java.lang.Runnable with single abstract method run() is a great example of functional interface.

    One of the major benefits of functional interface is the possibility to use lambda expressions to instantiate them. We can instantiate an interface with but the code looks bulky.

    Runnable r = new Runnable(){			@Override			public void run() {				System.out.println("My Runnable");			}};

    Since functional interfaces have only one method, lambda expressions can easily provide the method implementation. We just need to provide method arguments and business logic. For example, we can write above implementation using lambda expression as:

    If you have single statement in method implementation, we don’t need curly braces also. For example above Interface1 anonymous class can be instantiated using lambda as follows:

    Interface1 i1 = (s) -> System.out.println(s);		i1.method1("abc");

    So lambda expressions are a means to create anonymous classes of functional interfaces easily. There are no runtime benefits of using lambda expressions, so I will use it cautiously because I don’t mind writing a few extra lines of code.

    A new package java.util.function has been added with bunch of functional interfaces to provide target types for lambda expressions and method references. Lambda expressions are a huge topic, I will write a separate article on that in the future.

    You can read complete tutorial at .

    如果您注意到上述接口代码,则会注意到@FunctionalInterface 。 功能接口是Java 8中引入的新概念。具有一种抽象方法的接口就变成了功能接口。 我们不需要使用@FunctionalInterface批注将接口标记为Functional Interface。 @FunctionalInterface注释是一种避免在功能接口中意外添加抽象方法的工具。 您可以将其 ,这是使用它的最佳实践。 具有单个抽象方法run()的java.lang.Runnable是功能接口的一个很好的例子。

    功能接口的主要优点之一是可以使用lambda表达式实例化它们。 我们可以用实例化一个接口,但是代码看起来很庞大。

    由于功能接口只有一种方法,因此lambda表达式可以轻松提供该方法的实现。 我们只需要提供方法参数和业务逻辑。 例如,我们可以使用lambda表达式编写上面的实现:

    Runnable r1 = () -> {			System.out.println("My Runnable");		};

    如果方法实现中只有一条语句,那么我们也不需要花括号。 例如,上面的Interface1匿名类可以使用lambda实例化,如下所示:

    因此,lambda表达式是轻松创建功能接口的匿名类的一种方法。 使用lambda表达式没有运行时的好处,因此我会谨慎使用它,因为我不介意编写一些额外的代码行。

    添加了新的java.util.function包,其中包含许多功能接口,以提供lambda表达式和方法引用的目标类型。 Lambda表达式是一个巨大的话题,将来我将对此发表另一篇文章。

    您可以在阅读完整的教程。

  4. 用于集合上批量数据操作的Java Stream API (Java Stream API for Bulk Data Operations on Collections)

    A new java.util.stream has been added in Java 8 to perform filter/map/reduce like operations with the collection. Stream API will allow sequential as well as parallel execution. This is one of the best features for me because I work a lot with Collections and usually with Big Data, we need to filter out them based on some conditions.

    Collection interface has been extended with stream() and parallelStream() default methods to get the Stream for sequential and parallel execution. Let’s see their usage with simple example.

    package com.journaldev.java8.stream;import java.util.ArrayList;import java.util.List;import java.util.stream.Stream;public class StreamExample {	public static void main(String[] args) {				List
    myList = new ArrayList<>(); for(int i=0; i<100; i++) myList.add(i); //sequential stream Stream
    sequentialStream = myList.stream(); //parallel stream Stream
    parallelStream = myList.parallelStream(); //using lambda with Stream API, filter example Stream
    highNums = parallelStream.filter(p -> p > 90); //using lambda in forEach highNums.forEach(p -> System.out.println("High Nums parallel="+p)); Stream
    highNumsSeq = sequentialStream.filter(p -> p > 90); highNumsSeq.forEach(p -> System.out.println("High Nums sequential="+p)); }}

    If you will run above example code, you will get output like this:

    Notice that parallel processing values are not in order, so parallel processing will be very helpful while working with huge collections.

    Covering everything about Stream API is not possible in this post, you can read everything about Stream API at .

    Java 8 java.util.stream已添加了新的java.util.stream以对该集合执行类似于filter / map / reduce的操作。 Stream API将允许顺序执行和并行执行。 这对我来说是最好的功能之一,因为我经常处理Collections,而且通常使用Big Data,因此我们需要根据某些条件过滤掉它们。

    Collection接口已使用stream()parallelStream()默认方法进行了扩展,以获取用于顺序执行和并行执行的Stream。 让我们用一个简单的例子看看它们的用法。

    package com.journaldev.java8.stream;import java.util.ArrayList;import java.util.List;import java.util.stream.Stream;public class StreamExample {	public static void main(String[] args) {				List
    myList = new ArrayList<>(); for(int i=0; i<100; i++) myList.add(i); //sequential stream Stream
    sequentialStream = myList.stream(); //parallel stream Stream
    parallelStream = myList.parallelStream(); //using lambda with Stream API, filter example Stream
    highNums = parallelStream.filter(p -> p > 90); //using lambda in forEach highNums.forEach(p -> System.out.println("High Nums parallel="+p)); Stream
    highNumsSeq = sequentialStream.filter(p -> p > 90); highNumsSeq.forEach(p -> System.out.println("High Nums sequential="+p)); }}

    如果您将在示例代码上方运行,则将获得如下输出:

    请注意,并行处理值不按顺序排列,因此在处理大量集合时并行处理将非常有帮助。

    这篇文章无法涵盖有关Stream API的所有内容,您可以在阅读有关Stream API的所有内容。

  5. Java时间API (Java Time API)

    It has always been hard to work with Date, Time and Time Zones in java. There was no standard approach or API in java for date and time in Java. One of the nice addition in Java 8 is the java.time package that will streamline the process of working with time in java.

    Just by looking at Java Time API packages, I can sense that it will be very easy to use. It has some sub-packages java.time.format that provides classes to print and parse dates and times and java.time.zone provides support for time-zones and their rules.

    The new Time API prefers enums over integer constants for months and days of the week. One of the useful class is DateTimeFormatter for converting DateTime objects to strings.

    For complete tutorial, head over to .

    在Java中使用日期,时间和时区一直很困难。 Java中没有用于日期和时间的标准方法或API。 Java 8中一个不错的附加功能是java.time包,它将简化在Java中使用时间的过程。

    仅查看Java Time API软件包,我就可以感觉到它非常易于使用。 它具有一些java.time.format子包,这些子包提供了用于打印和解析日期和时间的类,而java.time.zone提供了对时区及其规则的支持。

    新的Time API在整月的几个月和一周中的几天中都比整数常量更喜欢枚举。 DateTimeFormatter是有用的类之一,用于将DateTime对象转换为字符串。

    有关完整的教程,请转到 。

  6. 集合API的改进 (Collection API improvements)

    We have already seen forEach() method and Stream API for collections. Some new methods added in Collection API are:

    • Iterator default method forEachRemaining(Consumer action) to perform the given action for each remaining element until all elements have been processed or the action throws an exception.
    • Collection default method removeIf(Predicate filter) to remove all of the elements of this collection that satisfy the given predicate.
    • Collection spliterator() method returning Spliterator instance that can be used to traverse elements sequentially or parallel.
    • Map replaceAll(), compute(), merge() methods.
    • Performance Improvement for HashMap class with Key Collisions

    我们已经看到了forEach()方法和用于集合的Stream API。 Collection API中添加的一些新方法是:

    • Iterator默认方法forEachRemaining(Consumer action)对剩余的每个元素执行给定的操作,直到处理完所有元素或该操作引发异常为止。
    • Collection默认方法removeIf(Predicate filter)删除此集合中满足给定谓词的所有元素。
    • Collection spliterator()方法返回Spliterator实例,该实例可用于顺序或并行遍历元素。
    • 映射replaceAll()compute()merge()方法。
    • 具有键冲突的HashMap类的性能改进
  7. 并发API改进 (Concurrency API improvements)

    Some important concurrent API enhancements are:

    • ConcurrentHashMap compute(), forEach(), forEachEntry(), forEachKey(), forEachValue(), merge(), reduce() and search() methods.
    • CompletableFuture that may be explicitly completed (setting its value and status).
    • Executors newWorkStealingPool() method to create a work-stealing thread pool using all available processors as its target parallelism level.

    一些重要的并发API增强功能包括:

    • ConcurrentHashMap (),forEach(),forEachEntry(),forEachKey(),forEachValue(),merge(),reduce()和search()方法。
    • 可以显式完成的CompletableFuture (设置其值和状态)。
    • Executors newWorkStealingPool()方法使用所有可用处理器作为目标并行度来创建窃取线程池。
  8. Java IO改进 (Java IO improvements)

    Some IO improvements known to me are:

    • Files.list(Path dir) that returns a lazily populated Stream, the elements of which are the entries in the directory.
    • Files.lines(Path path) that reads all lines from a file as a Stream.
    • Files.find() that returns a Stream that is lazily populated with Path by searching for files in a file tree rooted at a given starting file.
    • BufferedReader.lines() that return a Stream, the elements of which are lines read from this BufferedReader.

    我知道的一些IO改进是:

    • Files.list(Path dir)返回延迟填充的Stream,其元素是目录中的条目。
    • Files.lines(Path path) ,以流的形式从文件中读取所有行。
    • Files.find()通过在以给定起始文件为根的文件树中搜索文件来返回用Path Files.find()填充的Stream。
    • 返回一个Stream的BufferedReader.lines() ,其元素是从此BufferedReader读取的行。
  9. 其他核心API改进 (Miscellaneous Core API improvements)

    Some misc API improvements that might come handy are:

    1. static method withInitial(Supplier supplier) to create instance easily.
    2. interface has been extended with a lot of default and static methods for natural ordering, reverse order etc.
    3. min(), max() and sum() methods in Integer, Long and Double wrapper classes.
    4. logicalAnd(), logicalOr() and logicalXor() methods in Boolean class.
    5. .stream() method to get an ordered Stream over the ZIP file entries. Entries appear in the Stream in the order they appear in the central directory of the ZIP file.
    6. Several utility methods in Math class.
    7. jjs command is added to invoke Nashorn Engine.
    8. jdeps command is added to analyze class files
    9. JDBC-ODBC Bridge has been removed.
    10. PermGen memory space has been removed

    一些杂项API改进可能会派上用场:

    1. 静态方法可以使用Initial(供应商)轻松创建实例。
    2. 接口已扩展了许多默认和静态方法,用于自然排序,反向排序等。
    3. Integer,Long和Double包装器类中的min(),max()和sum()方法。
    4. 布尔类中的logicalAnd(),logicalOr()和logicalXor()方法。
    5. .stream()方法获取ZIP文件条目上的有序Stream。 条目以在ZIP文件的中央目录中出现的顺序出现在Stream中。
    6. Math类中的几种实用方法。
    7. 添加了jjs命令以调用Nashorn Engine。
    8. 添加了jdeps命令以分析类文件
    9. JDBC-ODBC桥已被删除。
    10. PermGen内存空间已被删除

That’s all for Java 8 features with example programs. If I have missed some important features of Java 8, please let me know through comments.

这就是带有示例程序的Java 8功能的全部。 如果我错过了Java 8的一些重要功能,请通过注释告知我。

翻译自:

java组合与继承始示例

转载地址:http://vtlzd.baihongyu.com/

你可能感兴趣的文章
20145202马超《java》实验5
查看>>
JQuery 事件
查看>>
main(argc,argv[])
查看>>
在线教育工具—白板系统的迭代1——bug监控排查
查看>>
121. Best Time to Buy and Sell Stock
查看>>
hdu 1005 根据递推公式构造矩阵 ( 矩阵快速幂)
查看>>
安装php扩展
查看>>
百度移动搜索主要有如下几类结果构成
查看>>
Python爬虫面试题170道:2019版【1】
查看>>
JavaBean规范
查看>>
第四阶段 15_Linux tomcat安装与配置
查看>>
NAS 创建大文件
查看>>
学习笔记-模块之xml文件处理
查看>>
接口测试用例
查看>>
面试:用 Java 实现一个 Singleton 模式
查看>>
Sybase IQ导出文件的几种方式
查看>>
案例:手动输入一个字符串,打散放进一个列表,小写字母反序 大写字母保持不变...
查看>>
linux 系统下 tar 的压缩与解压缩命令
查看>>
阿里负载均衡,配置中间证书问题(在starcom申请免费DV ssl)
查看>>
转:How to force a wordbreaker to be used in Sharepoint Search
查看>>