3.9 练习
练习的答案可以在GitHub代码仓库(https://github.com/RichardWarburton/java-8-Lambdas-exercises)中找到。
1.常用流操作。实现如下函数:
a. 编写一个求和函数,计算流中所有数之和。例如,int addUp(Stream ;
b. 编写一个函数,接受艺术家列表作为参数,返回一个字符串列表,其中包含艺术家的姓名和国籍;
c. 编写一个函数,接受专辑列表作为参数,返回一个由最多包含3首歌曲的专辑组成的列表。
2.迭代。修改如下代码,将外部迭代转换成内部迭代:
int totalMembers = 0;for (Artist artist : artists) {Stream<Artist> members = artist.getMembers();totalMembers += members.count();}
3.求值。根据Stream方法的签名,判断其是惰性求值还是及早求值。
a. boolean anyMatch(Predicate predicate);
b. Stream
4.高阶函数。下面的Stream函数是高阶函数吗?为什么?
a. boolean anyMatch(Predicate predicate);
b. Stream
- 纯函数。下面的Lambda表达式有无副作用,或者说它们是否更改了程序状态?
x -> x + 1
示例代码如下所示:
AtomicInteger count = new AtomicInteger(0);List<String> origins = album.musicians().forEach(musician -> count.incAndGet();)
a. 上述示例代码中传入forEach方法的Lambda表达式。 6. 计算一个字符串中小写字母的个数(提示:参阅String对象的chars方法)。 7. 在一个字符串列表中,找出包含最多小写字母的字符串。对于空列表,返回Optional对象。
