引言
在 Java8 之前,我们遍历集合总是一遍遍的写 for 循环,而且为了提高处理效率,需要利用多核架构。然而,编写并行代码是困难的,而且容易出错。所以,Java API设计人员定义 一个名为 Stream 的新抽象来更新API,该抽象允许以声明的方式处理数据。此外,流可以利用多核架构,而不必编写一行多线程代码。
JDK7:
List<Transaction> groceryTransactions = new Arraylist<>();
for(Transaction t: transactions){
if(t.getType() == Transaction.GROCERY){
groceryTransactions.add(t);
}
}
Collections.sort(groceryTransactions, new Comparator(){
public int compare(Transaction t1, Transaction t2){
return t2.getValue().compareTo(t1.getValue());
}
});
List<Integer> transactionIds = new ArrayList<>();
for(Transaction t: groceryTransactions){
transactionsIds.add(t.getId());
}
在JDK8中,上面的代码就可以写成如下:
JDK8:
List<Integer> transactionsIds =
transactions.stream()
.filter(t -> t.getType() == Transaction.GROCERY) //to filter elements given a predicate)
.sorted(comparing(Transaction::getValue).reversed())//to sort the elements given a comparator)
.map(Transaction::getId) //to extract information
.collect(toList());
图示:
Stream().filter(...).findAny().orElse(null):
List<String> adds=new ArrayList<>();
List<String> removes=new ArrayList<>();
for (TbClientModule tbClientModule : tbClientModules) {
Integer to = toModuleList.stream().filter(it->it.equals(Integer.parseInt(tbClientModule.getId().toString()))).findFirst().orElse(-1);
if(-1 != to){ //id相等
adds.add(to.toString());
}else{ //id不相等
removes.add(tbClientModule.getId().toString());
}
}
findFirst() 和 findAny() 差不多。具体待考究
forEach:
removes.forEach(item->{
modsArray.remove(item);
});
优质文章:https://www.oracle.com/technetwork/articles/java/ma14-java-se-8-streams-2177646.html
https://www.ibm.com/developerworks/cn/java/j-lo-java8streamapi/index.html
distinct:https://www.concretepage.com/java/jdk-8/java-8-distinct-example