标签:value operator parent java8 jdbc action gem spi under
You can omitted the type declaration of the right when working with Generics.
Map<String, List<Trade>> trades = new TreeMap<String, List<Trade>> ();
At now, case below is legal:
Map<String, List<Trade>> trades = new TreeMap <> ();
trades = new TreeMap()
is legal, but it will make the compiler generaqte a couple of type-safety warnings.
Switch statements work either with primitive types or enumerated types. Java 7 introduced another type that we can use in Switch statements: the String type.
Java 7 has introduced another cool feature to manage the resources automatically. It is simple in operation, too. All we have to do is declare the resources in the try as follows:
try(resources_to_be_cleant){
// your code
}
There can be multiple statments in the ()
sperated by semicolumn(;).
Behind the scenes, the resources that should be auto closed must implement java.lang.AutoCloseable interface.The AutoCloseable is the parent of java.io.Closeable interface and has just one method close() that would be called by the JVM when the control comes out of the try block.
Java 7 introduced underscores in identifying the places. For example, you can declare 1000 as shown below:
int thousand = 1_000;
Note that binary literals are also introduced in this release too.
In JDK 7, you can express literal values in binary with prefix ‘0b’ (or ‘0B’) for integral types (byte, short, int and long), similar to C/C++ language. Before JDK 7, you can only use octal values (with prefix ‘0’) or hexadecimal values (with prefix ‘0x’ or ‘0X’).
int mask = 0b01010000101;
The multiple exceptions are caught in one catch block by using a ‘|’ operator. This way, you do not have to write dozens of exception catches. However, if you have bunch of exceptions that belong to different types, then you could use “multi multi-catch” blocks too.
try{
methodThatThrowsThreeExceptions();
} catch(ExceptionOne e) {
// log and deal with ExceptionOne
} catch(ExceptionTwo | ExceptionThree e) {
// log and deal with ExceptionTwo and ExceptionThree
}
A new java.nio.file package consists of classes and interfaces such as Path, Paths, FileSystem, FileSystems and others.
A Path is simply a reference to a file path. It is the equivalent (and with more features) to java.io.File.
You can use other utility methods such as Files.copy(..) and Files.move(..) to act on a file system efficiently. Similarly, use the createSymbolicLink(..) method to create symbolic links using your code.
The WatchService API lets you receive notification events upon changes to the subject( directory or file).
Steps involved in implementing the API are:
WatchService
. The service consists of a queue to hold WatchKeys
.WatchService
.WatchKey
is placed into the queue.WatchKey
and invoke queries on it.Java7 introduce a feature that work will be distributed across multiple cores and then joined togather to return the result set, which is called Fork and Join framework.
Basically the Fork-Join breaks the task at hand into mini-tasks until the mini-task is simple enough that it can be solved without further breaakups. It’s like a divide-and-conquer algorithm. One important concept to note in this framework is that ideally no worker thread is idle. They implement a work-stealing algorithm in that idle workers “steal” the work from those workers who are busy.
The core classes supporting the Fork-Join mechanism are ForkJoinPool
and ForkJoinTask
. The ForkJoinPool
is basically a specializzed implmentation of ExecutorService implementing the work-stealing algorithm. The ForkJoinTask
handle the problems need to be solved. There are two implmentations of this class out of the box: the RecursiveAction
and RecursiveTask
. You can extend these classes and override the compute method. The only difference between between them is that the former one does not return a value while the latter returns an object of specified type. Finally, provide the ForkJoinTask
to the Executor
by calling invoke method on the ForkJoinPool
.
In Java 7, a new feature called invokedynamic was introduced. This makes VM changes to incorporate non-Java language requirements. A new package, java.lang.invoke, consisting of classes such as MethodHandle, CallSite and others, has been created to extend the support of dynamic languages.
Java 8 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 sperate location that we can reuse.
myList.forEach(new Consumer<Integer>() {
public void accept(Integer t) {
System.out.println("forEach anonymous class Value::"+t);
}
});
In java8, we can use default
and static
keyword to create interfaces with method implementation. As to the Diamond Problem, the solution is that compiler will throw exception and we will have to provide implementation logic in the class implementing the interfaces.
菱形问题(diamond problem),就是说,当A的子类B和C同时实现了A中的方法,则同时继承了B和C的子类D在调用该方法时会出现混乱,无法得知该调用哪一个方法。
An interface with exactly one abstract method becomes Functional Interface. @FunctionalInterface annotation is optional. @FunctionalInterface annotation is a facility to avoid accidental addition of abstract methods in the functional interfaces.
One of the major benefits of functional interface is the possibility to use lambda expressions to instantiate them.
A new java.util.stream has been added in Java8 to perform filter/map/reduce like operations with the collection. Stream API will allow sequential as well as parallel execution.
Collection interface has been extended with stream() and parallelStream() default methods to get the Stream for sequential and parallel execution.
java.time package in Java 8 will streamline the process of working with time in java. 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 useful class is DateTimeFormatter for converting datetime objects to strings.
Beside forEach() method and Stream API for collections, there are other new methods:
Collection
default method removeId(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.repllaceAll()
, compute()
, merge()
methods.ConcurrentHashMap
compute(), forEach(), forEachEntry(), forEachKey(), forEachValue(), merge(), reduce() and search() methods.CompletableFuture
that may be explicitly completed(setting it’s value and status).Method reference can be used as a shorter and more readable alternative for a lambda expression which only calls an existing method. There are four varianrs of method references.
boolean isReal = list.stream().anyMatch(User::isRealUser);
User user = new User();
boolean isLegalName = list.stream().antMatch(user::isLegalName);
long count = list.stream().filter(String::isEmpty).count();
Stream<User> stream = list.stream().map(User::new);
Java 8 Optional class can help to handle situations where there is a possibility of getting the NullPointerException(NPE). It works as a container for the object of type T. It can return a value of this object if this value is not a null. When the value inside this container is null it allows doing some predefined actions instead of throwing NPE.
Optional<String> optional = Optional.empty();
String str = "value";
Optional<String> optional = Optional.of(str);
Optional<String> optional = Optional.ofNullable(getString());
List<String> listOpt = getList().orElseGet(() -> new ArrayList<>());
Optional<User> user = Optional.ofNullable(getUser());
String result = user
.map(User::getAddress)
.map(Address::getStreet)
.orElse("not specified");
We used the map() method to convert results of calling the getAddress() to the Optional
and getStreet() to Optional. If any of these methods returned null the map() would return an empty Optional.
String value = null;
Optional<String> valueOpt = Optional.ofNullable(value);
String result = valueOpt.orElseThrow(CustomException::new).toUpperCase();
This usage change NPE with another exception.
Java 8 is introducing a completely new JVM JavaScript engine - Nashorn. This engine makes unique use of some of the new features introduced in Java 7 such as invokeDynamic to provide JVM-level speed to JavaScript Execution right there with the likes of V8 and SpiderMonkey.
标签:value operator parent java8 jdbc action gem spi under
原文地址:https://www.cnblogs.com/helloz/p/9309315.html