码迷,mamicode.com
首页 > 编程语言 > 详细

Java8基础案例

时间:2017-12-18 18:37:44      阅读:155      评论:0      收藏:0      [点我收藏+]

标签:dex   markdown   import   exp   sed   on()   end   操作   data   

类构造器引用

首先看个简单的例子:

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 语法就是构造器引用
调用的是默认的构造函数。

类静态方法引用

首先看下简单的例子:

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 就是静态方法引用的实现。

类方法引用和实例方法引用

首先来看一个简单的例子:

类方法引用
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);

很遗憾实例方法引用的编译的时候报错了。

类型推测机制

当使用范型类时编译器可以自动推断出确定的参数类型。

public class Value< T > {
    public static< T > T defaultValue() { 
        return null; 
    }
}

Java8写法:
Value.defaultValue()

Java7写法:
Value<String>.defaultValue()

编译器特性

字节码中参数名字保留

先来看一个例子:

Method method = Main.class.getMethod("main", String[].class);
        for (final Parameter parameter : method.getParameters()) {
            System.out.println(" parameter : " + parameter.getName());
        }
        
不开启编译器优化:
parameter : arg0

开启编译器优化:
parameter : args

处理空指针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

Stream

forEach

首先看一个简单的例子:

Arrays.asList("a", "b", "c").forEach(s -> System.out.println(s));

遍历结果集并打印字符串

来看看forEach接口的定义:

package java.lang;
public interface Iterable<T> {

    /**
     * Performs the given action for each element of the {@code Iterable}
     * until all elements have been processed or the action throws an
     * exception.  Unless otherwise specified by the implementing class,
     * actions are performed in the order of iteration (if an iteration order
     * is specified).  Exceptions thrown by the action are relayed to the
     * caller.
     *
     * @implSpec
     * <p>The default implementation behaves as if:
     * <pre>{@code
     *     for (T t : this)
     *         action.accept(t);
     * }</pre>
     *
     * @param action The action to be performed for each element
     * @throws NullPointerException if 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);
        }
    }
}

可见接口上定义的是一个默认方法,这是jdk1.8的新特性,允许在接口上定义方式,这是集合类型最基础的实现。

ArrayList也重写了forEach方法:

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

在Java8中,Base64是一个标准库

    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);
    }

日期处理

        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

参考资料

Java8基础案例

标签:dex   markdown   import   exp   sed   on()   end   操作   data   

原文地址:http://www.cnblogs.com/loveyx/p/8058039.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!