标签:ide mamicode tor tostring cas 构造 sys 方法 rgs
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);
}
}
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);
}
}
标签:ide mamicode tor tostring cas 构造 sys 方法 rgs
原文地址:https://www.cnblogs.com/fly-book/p/12637909.html