方法引用构造函数引用
Posted fly-book
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了方法引用构造函数引用相关的知识,希望对你有一定的参考价值。
import java.util.Arrays;
import java.util.List;
import static java.util.Comparator.comparing;
/**
* 方法引用
*/
public class Quote{
public static void main(String[] args){
List<Apple> list = Arrays.asList(new Apple("red",120),new Apple("green",100));
list.sort(comparing(Apple::getWeight));
System.out.println(list);
List<String> str = Arrays.asList("a","b","A","B");
// str.sort((s1,s2)->s1.compareToIgnoreCase(s2));
str.sort(String::compareToIgnoreCase);
System.out.println(str);
}
}
![技术图片](https://image.cha138.com/20210625/02afe21d3268416cb4839c555236e735.jpg)
构造函数引用
public class Apple {
private String color;
private int weight;
public Apple() {
}
public Apple(int weight) {
this.weight = weight;
}
public Apple(String color) {
this.color = color;
}
public Apple(String color, int weight) {
this.color = color;
this.weight = weight;
}
public int getWeight() {
return weight;
}
public void setWeight(int weight) {
this.weight = weight;
}
public String getColor() {
return color;
}
public void setColor(String color) {
this.color = color;
}
@Override
public String toString() {
return "Apple{" +
"color=‘" + color + ‘‘‘ +
", weight=" + weight +
‘}‘;
}
}
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.function.BiFunction;
import java.util.function.Function;
import java.util.function.Supplier;
/**
* @FunctionalInterface
* public interface Supplier<T> {
* T get();
* }
*/
public class Demo {
public static List<Apple> map(List<Integer> list,Function<Integer,Apple> f){
List<Apple> res = new ArrayList<>();
for (Integer e : list) {
res.add(f.apply(e));
}
return res;
}
public static void main(String[] args){
/**
* 等价于
* Supplier<Apple> c2 = () -> new Apple();
* Apple apple = c2.get();
*/
Supplier<Apple> c1 = Apple::new;
Apple apple = c1.get();
/**
* 等价于
* Function<String,Apple> c2 = Apple::new;
* Apple a2 = c2.apply("red");
*/
Function<String,Apple> c2 = Apple::new;
Apple a2 = c2.apply("red");
//传递给了Apple的构造函数
List<Integer> weights = Arrays.asList(1,3,4,2,5);
List<Apple> apples = map(weights,Apple::new);
System.out.println(apples);
/**
* 等价于
* BiFunction<String,Integer,Apple> c3 = (color,weight) -> new Apple(color,weight);
* Apple a3 = c3.apply("green",110);
*/
//具有两个参数的构造函数Apple(String color, Integer weight)
BiFunction<String,Integer,Apple> c3 = Apple::new;
Apple a3 = c3.apply("red",110);
System.out.println(a3);
}
}
以上是关于方法引用构造函数引用的主要内容,如果未能解决你的问题,请参考以下文章