Class constructor Reference
Let's look at a simple example:
public class Car { public static Car create(final Supplier<Car> supplier) { return supplier.get(); } public void repair() { System.out.println("Repair: " + this.toString()); }}public class Main { public static void main(String[] args) { Car car = Car.create(Car::new); car.repair(); }}
Class::new syntax is a constructor reference
The default constructor is called.
Class static method reference
First look at the simple example:
public class Car { public static Car create(final Supplier<Car> supplier) { return supplier.get(); } public static void collect(final Car car) { System.out.println("Collected " + car.toString()); } public void repair() { System.out.println("Repair: " + this.toString()); }}Arrays.asList(Car.create(Car::new), Car.create(Car::new)).forEach(Car::collect);
Car::collect is the implementation of a static method reference.
class method Reference and instance method reference
Let's start with a simple example:
类方法引用Arrays.asList(Car.create(Car::new)).forEach(Car::repair);实例方法引用 final Car car = Car.create(Car::new); Arrays.asList(Car.create(Car::new)).forEach(car::repair);
很遗憾实例方法引用的编译的时候报错了。
Type inference mechanism
When using the generic class, the compiler can automatically infer the identified parameter types.
public class Value< T > { public static< T > T defaultValue() { return null; }}Java8写法:Value.defaultValue()Java7写法:Value<String>.defaultValue()
Compiler attribute byte code in Parameter name reserved
Let's look at an example:
Method method = Main.class.getMethod("main", String[].class); for (final Parameter parameter : method.getParameters()) { System.out.println(" parameter : " + parameter.getName()); } 不开启编译器优化:parameter : arg0开启编译器优化:parameter : args
Handling NULL pointer optional
Integer a = null; String b = "haha"; String c = null; Optional<Integer> opA = Optional.ofNullable(a); Optional<String> opB = Optional.ofNullable(b); Optional<String> opC = Optional.ofNullable(c); System.out.println("opA is null? " + (opA.isPresent() ? "否" : "是")); // 注意isPresent是反模式,即isNotNull的意思 System.out.println("opA : " + (opA.orElse(-1))); // print: -1 System.out.println("opB : " + (opB.orElseGet(() -> "none"))); // print: haha System.out.println("opB : " + opB.map(s -> "jxp say:" + s).orElse("jxp say: none")); // opB : jxp say:haha System.out.println("opC : " + opC.map(s -> "jxp say:" + s).orElse("jxp say: none")); // opB : jxp say:haha
Streamforeach
Let's look at a simple example:
Arrays.asList("a", "b", "c").forEach(s -> System.out.println(s));
Traverse the result set and print the string
Look at the definition of the Foreach interface:
Package Java.lang;public interface Iterable<t> {/** * performs the given action for each element Of the {@code iterable} * until all elements has been processed or the action throws an * exception. Unless otherwise specified by the implementing class, * actions is performed in the Order of iteration (if an Iterati On order * is specified). Exceptions thrown by the action is relayed to the * caller. * * @implSpec * <p>the default implementation behaves as if: * <pre>{@code * for (T t:th IS) * action.accept (t); *}</pre> * * @param action the action to being performed for each element * @throws NullPointerException I f The specified action is NULL * @since 1.8 */default void ForEach (CONSUMER<? Super T> Action) { Objects.requirenonnull (action); for (t t:this) {action.accept (t); } }}
A default method is defined on the visible interface, which is a new feature of jdk1.8 that allows you to define the method on the interface, which is the most basic implementation of the collection type.
ArrayList also overrides the Foreach method:
package java.util;public class ArrayList<E> extends AbstractList<E> implements List<E>, RandomAccess, Cloneable, java.io.Serializable{ @Override public void forEach(Consumer<? super E> action) { Objects.requireNonNull(action); final int expectedModCount = modCount; @SuppressWarnings("unchecked") final E[] elementData = (E[]) this.elementData; final int size = this.size; for (int i=0; modCount == expectedModCount && i < size; i++) { action.accept(elementData[i]); } if (modCount != expectedModCount) { throw new ConcurrentModificationException(); } }}
Filter
private static void useStreamFilter() { List<User> users = Arrays.asList( new User(1, "jiangxp", 10), new User(2, "jiangyx", 13), new User(3, "wanglf", 5)); List<User> filterUsers = users.stream().filter(s -> s.getAge() > 10).collect(Collectors.toList()); filterUsers.forEach(x -> System.out.println(x)); // filter 不会执行结果操作,而是将行为添加到stream提供的操作管线当中,只有执行最后的结果操作时,才会触发filter行为。 }
Parallel
private static void useStreamParallel() { List<User> users = Arrays.asList( new User(1, "jiangxp", 10), new User(2, "jiangyx", 13), new User(3, "wanglf", 5)); Integer totalAge = users.stream().parallel().map(s -> s.getAge()).reduce(0, Integer::sum); System.out.println(totalAge); // T reduce(T identity, BinaryOperator<T> accumulator); // public static int sum(int a, int b) { // return a + b; // } // 这两个是如何关联起来的? }
Collect
private static void useStreamCollectGroupBy() { List<User> users = Arrays.asList( new User(1, "jiangxp", 10), new User(2, "jiangyx", 13), new User(3, "wanglf", 10)); Map<Integer, List<User>> res = users.stream().collect(Collectors.groupingBy(s -> s.getAge())); res.forEach((k, v) -> { System.out.println(k); v.forEach(s -> System.out.println(s)); }); }
Base64
In Java8, Base64 is a standard library
private static void useBase64() { final String text = "我是中国人"; final String encoded = Base64.getEncoder().encodeToString(text.getBytes(StandardCharsets.UTF_8)); System.out.println(encoded); final String decoded = new String(Base64.getDecoder().decode(encoded), StandardCharsets.UTF_8); System.out.println(decoded); }
Date processing
LocalDateTime now = LocalDateTime.now(); System.out.println(now); // 2017-07-06T10:38:35.043 System.out.println(LocalDateTime.now().format(DateTimeFormatter.ofPattern("yyyy-MM-dd"))); // 2017-07-06 System.out.println(LocalDateTime.now().format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss"))); // 2017-07-06 10:38:35 String date = "2017-07-06"; LocalDate d1 = LocalDate.parse(date); System.out.println(d1); // 2017-07-06 String date2 = "2017-07-06 10:38:35"; LocalDateTime d2 = LocalDateTime.parse(date2, DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss")); System.out.println(d2); // 2017-07-06T10:38:35
Resources
JAVA8 Basic Case