Java8函数式编程

2. Lambda表达式

button.addActionListener(new ActionListener() {

    public  void actionPerformed(ActionEvent event) {

        System.out.println("button clicked");

    }

});

变成—–>


button.addActionListener(event -> System.out.println("button clicked"));
2.1. 各种类型的lambda表达式

Runnable anArgments = () -> System.out.println("Hello World");

ActionListener oneArgment = event -> System.out.println("button clicked");

Runnable anArgments = () -> {

    System.out.println("Hello World");

    System.out.println("Hello World");

};

BinaryOperator<Long> add = (x, y) -> x + y;

BinaryOperator<Long> add = (Long x, Long y) -> x + y;

Lamba表达式中使用方法中的变量时,变量其实相当于添加了final属性

2.2. 函数接口

函数接口是只有一个抽象方法的接口,用作Lambda表达式的类型

3. 流

int count = 0;
for (Artist artist : allArtists) {
   if (artist.isFrom("London")) {
       count++;
   }
}

—>转化为


long count = allArtists.stream()
       .filter(artist -> artist.isFrom("London"))
       .count();
3.1 常用流操作

//collect(toList())

List<String> collected = Stream.of("a","b","c").collect(Collectors.toList());

//map

List<String> collected = Stream.of("a","b","hello").map(string -> string.toUpperCase()).collect(toList());

//filter

List<String> beginningWithNumbers = Stream.of("a","1abc","abc1").filter(value -> isDigit(value.charAt(0))).collect(toList());

//flatMap

List<Integer> together = Stream.of(asList(1, 2), asList(3, 4)).flatMap(numbers -> numbers.stream()).collect(toList());

//max&min

Track shortestTrack = tracks.stream().min(Comparator.comparing(track -> track.getLength())).get()

//reduce求和

int count = Stream.of(1, 2, 3).reduct(0, (acc, element) -> acc + element);


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值