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

https://www.ibm.com/developerworks/cn/java/j-lo-java8streamapi/index.html

distinct:https://www.concretepage.com/java/jdk-8/java-8-distinct-example

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值