Java8
函数式接口
Predicate T->booleanIntPredicate LongPredicate DoublePredicate
Consumer T->void
IntConsumer LongConsumer DoubleConsumer
Function T->R
IntFunction
IntToDoubleFunction
IntToLongFunction
LongFunction
LongToDoubleFunction
LongToIntFunction
DoubleFunction
ToIntFunction
ToLongFunction
ToDoubleFunction
Supplier ()->T
BooleanSupplier
IntSupplier
LongSupplier
DoubleSupplier
UnarryOperator T->T
IntUnaryOperator
LongUnaryOperator
DoubleUnaryOperator
BinaryOperator (T,T)->T
IntBinaryOperator
LongBinaryOperator
DoubleBinaryOperator
BiPredicate (L,R)->boolean
BiConsumer (L,R)->void
ObjIntConsumer
ObjLongConsumer
ObjDoubleConsumer
BiFunction (T,U)->R
ToIntBiFunction
ToLongBiFunction
ToDoubleFunction
复合lambda表达式
List list = Arrays.asList(new Apple(2), new Apple(3), new Apple(1), new Apple(4), new Apple(5));
list.sort(Comparator.comparing(Apple::getWeight));
//排序,调用Apple getWeight方法进行排序
比较器复合
List list = Arrays.asList(new Apple(2,"China"), new Apple(2,"Azk"), new Apple(1,"Korea"), new Apple(4,"Japan"), new Apple(5,"China"));
list.sort(Comparator.comparing(Apple::getWeight).reversed().thenComparing(Apple::getCountry));
//排序,先用重量排序,然后在反转,然后在根据国家排序
谓词复合
public static voidmain(String[] args) {
List list = Arrays.asList(new Apple(2, "China"), new Apple(2, "Azk"), new Apple(1, "Korea"), new Apple(4, "Japan"), new Apple(5, "China"));
list.sort(Comparator.comparing(Apple::getWeight).reversed().thenComparing(Apple::getCountry));
Predicate applePredicate1=(Apple apple)->apple.getWeight()>2;
Predicate applePredicate2= ((Predicate) apple -> apple.getWeight() > 2).and(apple -> apple.getCountry().equals("China"));
//筛选 苹果的重量大于2,同时属于China
testFuHe(list,applePredicate2);
}public static List testFuHe(List apples, Predicatepredicate) {
ArrayList as = new ArrayList<>();for(Apple apple : apples) {if(predicate.test(apple)) {
as.add(apple);
}
}returnas;
}
函数复合
Function fun1=(num)->num*10;
Function fun2=(num)->num+10;
Function fun3 = fun1.andThen(fun2); //调完fun1 在调用fun2
Function fun4 = fun1.compose(fun2); //调用fun2的结果 然后在调用fun1
Integer res3= fun3.apply(5);
Integer res4= fun4.apply(5);
流处理
流只能遍历一次。遍历完之后这个流就已经被消费掉了
流的Api
filter 中间 Stream Predicate T->boolean
map 中间 Stream Function T->R
limit 中间 Stream
sorted 中间 Stream Compartor (T,T)->int
distinct 中间 Stream
flatMap 中间 Stream Function> T->Stream
forEach 终端 Comsumer T->void 消费每个流的元素,返回一个void
count 终端 返回流中元素的个数。
collect 终端 把流归成一个集合,比如List,Map甚至Integer
reduce 终端 Optional BinaryOperator (T,T)->T
匹配
anyMatch 终端 Predicate T->boolean 看当中是否有一个匹配
allMatch 终端 Predicate T->boolean 看当中是否全部匹配
noMatch 终端 Predicate T->boolean 确保没有匹配
查找
findAny 终端 Optional 返回当前流的任意元素
findFirst 终端 Optional 查找第一个
数值
sum
min
max
案例
public classTrader {privateString name;privateString city;publicTrader(String name, String city) {this.name =name;this.city =city;
}publicString getName() {returnname;
}public voidsetName(String name) {this.name =name;
}publicString getCity() {returncity;
}public voidsetCity(String city) {this.city =city;
}
@OverridepublicString toString() {return "Trader{" +
"name=‘" + name + ‘\‘‘ +
", city=‘" + city + ‘\‘‘ +
‘}‘;
}
}
public classTransaction {privateTrader trader;private intyear;private intvalue;public Transaction(Trader trader, int year, intvalue) {this.trader =trader;this.year =year;this.value =value;
}publicTrader getTrader() {returntrader;
}public voidsetTrader(Trader trader) {this.trader =trader;
}public intgetYear() {returnyear;
}public void setYear(intyear) {this.year =year;
}public intgetValue() {returnvalue;
}public void setValue(intvalue) {this.value =value;
}
}
public static voidmain(String[] args) {
Trader raoul= new Trader("Raoul", "Cambridge");
Trader mario= new Trader("Mario", "Milan");
Trader alan= new Trader("Alan", "Cambridge");
Trader brian= new Trader("Brian", "Cambridge");
List transactions =Arrays.asList(new Transaction(brian, 2011, 300),new Transaction(raoul, 2012, 1000),new Transaction(raoul, 2011, 400),new Transaction(mario, 2012, 710),new Transaction(mario, 2012, 700),new Transaction(alan, 2012, 950)
);//找出2011年发生的所有交易,并按交易额排序(从低到高)。
List res1 = transactions.stream().filter(transaction -> transaction.getYear() == 2011)
.sorted(Comparator.comparing(Transaction::getValue)).collect(Collectors.toList());//交易员都在哪些不同的城市工作过?
List res2 = transactions.stream().map(transaction ->transaction.getTrader().getCity()).distinct().collect(Collectors.toList());//查找所有来自于剑桥的交易员,并按姓名排序。
List res3 = transactions.stream().filter(transaction ->transaction.getTrader()
.getCity().equals("Cambridge")).sorted(Comparator.comparing(o ->o.getTrader().getName())).collect(Collectors.toList());//返回所有交易员的姓名字符串,按字母顺序排序。
List res4 = transactions.stream().flatMap((Function>) transaction ->Stream.of(transaction.getTrader().getName()))
.sorted().collect(Collectors.toList());//有没有交易员是在米兰工作的?
Optional res5 = transactions.stream().filter(transaction -> transaction.getTrader().getCity().equals("Milan")).findAny();//打印生活在剑桥的交易员的所有交易额。
transactions.stream().filter(transaction -> transaction.getTrader().getCity().equals("Cambridge"))
.flatMap((Function>) transaction ->Stream.of(transaction.getValue())).forEach(System.out::println);//所有交易中,最高的交易额是多少?
Optional res6 =transactions.stream().max(Comparator.comparingInt(Transaction::getValue));//找到交易额最小的交易。
Optional res7 =transactions.stream().min(Comparator.comparingInt(Transaction::getValue));
}
构建流
由值创建流
Stream.of();
Stream stringStream = Stream.of("one", "two", "three");
由数组创建流
Arrays.stream();
int[] nums={2,3,4,5,6};
IntStream stream = Arrays.stream(nums);