Java8 Stream 和 forEach

引言

在 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());

 

圖示:

streams-f2

 

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

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章