java8 stream代替for循环 具体实战

1.使用stream求集合中对象的某2个属性的和

List list = new ArrayList();

MacTicket ticket = new MacTicket();

ticket .setNum(1);

ticket.setAmount(2);

MacTicket ticket1 = new MacTicket();

ticket1.setNum(1);

ticket1.setAmount(2);

list.add(ticket);

list.add(ticket1);

int sum =list.stream().filter(tikcet->ticket.getNum()!=null&&ticket.getAmount()!=null).mapToInt(ticket->{return ticket.getNum()+ticket.getAmount();}).sum();

filter中间流,参数为Functional的Interface,形参为lambda表达式即匿名函数,ticket为函数的入参,箭头为分隔符 →右边是函数体

mapToInt比map方法的好处是避免了装箱和拆箱的额外开销,sum为归约函数。

2.

https://docs.oracle.com/javase/8/docs/api/java/util/stream/package-summary.html

你可能感兴趣的:(java8)