Java 8 method references
In Java 8, we can use class::methedName syntax to refer to methods from classes or objects. Let me take a look at method references
1. The type of method reference
Method references | describe | Method reference instance |
---|---|---|
A static method | Used to reference static methods in a class | Math: Max is equivalent to Math.(x,y) |
Methods from the instance | Reference the instance method using a reference to the supplied object | System.out::println = system.out.println (x) |
Instance method of a class type | Invoke instance methods on object references provided by the context | String::length is equivalent to str.length |
The constructor | A reference to a constructor function | ArrayList::new equals new ArrayList() |
2 References to static methods
An example using math.max ()
List<Integer> integers = Arrays.asList(1.12.433.5);
Optional<Integer> max = integers.stream().reduce( Math::max );
max.ifPresent(value -> System.out.println(value));
Copy the code
3. Method references to method instance methods
List<Integer> integers = Arrays.asList(1.12.433.5);
Optional<Integer> max = integers.stream().reduce( Math::max );
max.ifPresent( System.out::println );
Copy the code
4. Class type references to instance methods
List<String> strings = Arrays
.asList("how"."to"."do"."in"."java"."dot"."com");
List<String> sorted = strings
.stream()
.sorted((s1, s2) -> s1.compareTo(s2))
.collect(Collectors.toList());
System.out.println(sorted);
List<String> sortedAlt = strings
.stream()
.sorted(String::compareTo)
.collect(Collectors.toList());
System.out.println(sortedAlt);
Copy the code
5. Constructor references
We can update the first method, which creates a list of integers from 1 to 100. Using Lambda expressions is fairly simple. To create a new instance of ArrayList, we use ArrayList::new
List<Integer> integers = IntStream
.range(1.100)
.boxed()
.collect(Collectors.toCollection( ArrayList::new ));
Optional<Integer> max = integers.stream().reduce(Math::max);
max.ifPresent(System.out::println);
Copy the code