JDK8 feature operator :: method reference static method instance method construction method

Operators in JDK8 :: ​​method references can be retrieved

Take the Collections.sort()method as an example

/**
 * 静态方法引用
 * 实例方法引用
 * 构造方法引用
 *
 */
public class MethodTest {
    public static List<Box> list;

    static {
        list = new ArrayList<>();
        for (int i = 1; i <= 5; i ++) {
            list.add(
                    new Box(
                            new Random().nextInt(10) + 1,
                            new Random().nextInt(10) + 1,
                            new Random().nextInt(10) + 1
                    )
            );
        }
        System.out.println(list);
    }

    public static void main(String[] args) {
        // 匿名内部类实现
        Collections.sort(list, new Comparator<Box>() {
            @Override
            public int compare(Box o1, Box o2) {
                return o1.getVolume() - o2.getVolume();
            }
        });
        System.out.println(list);

        // Lambda实现
        Collections.sort(list, (o1, o2) -> o1.getVolume() - o2.getVolume() );
        System.out.println(list);

        // 静态方法引用实现
        Collections.sort(list, Box::compareStatic);
        System.out.println(list);

        // 实例方法引用实现
        Box box = new Box();
        Collections.sort(list, box::compareInstance);
        System.out.println(list);

        // 构造方法引用 (实例化对象)
        GetBox getBox = Box::new;
        Box box1 = getBox.get(5, 10, 15);
        System.out.println(box1);
    }
}

interface GetBox {
    Box get(int width, int height, int length);
}

Guess you like

Origin www.cnblogs.com/esrevinud/p/12732261.html