1. 程式人生 > >java8:Stream例子

java8:Stream例子

1.

//在 7 中,要發現 type = grocery 的所有交易,然後返回以交易值降序排序好的交易 ID 集合
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());
}

//java8
List<Transaction> transactionIds = transactions.parallelStream()
    .fliter(t->t.getType()==Transaction.GROCERY)
    .sorted(comparing(Transaction::getValue).reversed)
    .map(Transaction::getId)
    .collect(toList());