流使用介绍:
计算结构:
副作用:
示例1:有副作用的代码
mapfreq = new hashmap<>(); try (stream words = new scanner(file).tokens()) { words.foreach(word -> { freq.merge(word.tolowercase(), 1l, long::sum); }); }
问题:这段代码使用foreach来修改外部状态(freq)。它是迭代的并且不利用流。
示例2:无副作用的代码
mapfreq; try (stream words = new scanner(file).tokens()) { freq = words.collect(collectors.groupingby(string::tolowercase, collectors.counting())); }
解决方案: 使用 collectors.groupingby 收集器创建频率表,而不改变外部状态。更短、更清晰、更高效。
流api的占用:
收藏家:
示例 3:提取最常见的十个单词的列表
listtopten = freq.entryset().stream() .sorted(map.entry. comparingbyvalue().reversed()) .limit(10) .map(map.entry::getkey) .collect(collectors.tolist());
说明:
收集器 api 的复杂性:
地图和收集攻略:
示例4:使用带有合并功能的tomap
mapfreq; try (stream words = new scanner(file).tokens()) { freq = words.collect(collectors.tomap( string::tolowercase, word -> 1l, long::sum )); }
说明:
示例 5:按艺术家对专辑进行分组并查找最畅销的专辑
map topalbums = albums.stream()
.collect(collectors.tomap(
album::getartist,
function.identity(),
binaryoperator.maxby(comparator.comparing(album::sales))
));
说明:
字符串集合:
collectors.joining 使用可选分隔符连接字符串。
示例 6:使用分隔符连接字符串
String result = Stream.of("came", "saw", "conquered")
.collect(Collectors.joining(", ", "[", "]"));
说明:
结论: