这本书内容精炼,每章结束都做了总结,从后往前看更好些。
第九章 使用Lamdba表达式编写并发程序使用非阻塞式编程的原因是, 阻塞式IO 将系统扩展至支持大量用户时,需要和服务器建立大量TCP连接。
使用了一个聊天室应用的例子。
第八章 设计和架构的原则
Lamdb表达式的一些变形,现实的例子,使用严格设计的不多见,看看例子,涨涨思路即可。
设计模式的几个特点, 抽象原则(依赖反转原则)、单一功能原则、开闭原则、少用继承多用组合(高内聚低耦合)。
第七章
loger的例子代码没写通
重构的例子 ,ok
public class Track {
// 歌曲名
private String name;
// 歌曲演唱者
private List<String> musicianList;
// 歌曲长度
private Integer length;
// 歌词曲
private String content;
}
专辑//歌曲专辑
public class Album {
//歌曲数
private Integer length;
//歌曲列表
private List<Track> tracksList;
}
测试方式// 算所有专辑的歌曲总数
list.stream().mapToLong(temp -> temp.getLength()).sum();
// 算出所有专辑中的音乐作者的数量和
list.stream().mapToLong(temp -> temp.getTracksList().stream().mapToLong(a -> a.getMusicianList().size()).sum())
.sum();
// 算出所有专辑的时长和
list.stream().mapToLong(temp -> temp.getTracksList().stream().mapToLong(a -> a.getLength()).sum()).sum();
这样写的话,会有很多重复的写法,比如 temp -> temp.getTracksList().stream()
所以改写
// 计算专辑列表中的歌曲的总时长
public long countFeature(ToLongFunction<Album> function){
return list.stream().mapToLong(function).sum();
}
//歌曲总数
public long countTrack(){
return countFeature(album->album.getLength());
}
//歌曲总时长
public long lenghtTrack(){
return countFeature(album->album.getTracksList().stream().mapToLong(a->a.getLength()).sum());
}
//歌手总数
public long lenghtMusician(){
return countFeature(album->album.getTracksList().stream().mapToLong(a->a.getMusicianList().size()).sum());
}
还可以精简,马未都说,看历史书看的是道理,如果把它当成事实就无趣了。到此为止。Lamdba表达式的单元测试
把实现功能放在函数里,有利于单元测试。如把一组字符串的首字母大写:
//字符串首字母大写
public static List<String> upperLetter(List<String> words){
return words.stream().map(
temp->{
char firstChar=Character.toUpperCase(temp.charAt(0));
return firstChar+temp.substring(1);
}).collect(Collectors.toList());
}
//更友好的写法
public static List<String> upperLetter_f(List<String> words){
return words.stream().map(
temp->firstUpper(temp)).collect(Collectors.toList());
}
//首字母大写
public static String firstUpper(String temp){
char firstChar=Character.toUpperCase(temp.charAt(0));
return firstChar+temp.substring(1);
}
peek 在流中间设置断点stream对象在forEach后返回空值,导致需要多次访问。
//如果同时打印出字符串可以这样写
public static List<String> upperLetter_d(List<String> words){
return words.stream()
.map(temp -> firstUpper(temp))
.peek(action->System.out.println(action))
.collect(Collectors.toList());
}
以上为第7、8、9章的内容。